Android獲得statusBar高度

傲慢的上校發表於2013-08-23

     在畫UI過程中,有些情況下需要知道statusBar高度:

網上有些方法是這樣的:

Rect frame = new Rect();
		getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;
		Log.v("@@@@@@", "the statusbar Height is : " + statusBarHeight);

類似:

int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
		//statusBarHeight是上面所求的狀態列的高度
		int titleBarHeight = contentTop - statusBarHeight;		
		Log.v("@@@@@@", "the titleBar Height is : " + titleBarHeight);

或者:

Rect rect = new Rect();
        MainActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        View view = MainActivity.this.getWindow().findViewById(Window.ID_ANDROID_CONTENT);
        int topS = rect.top;//狀態列高度
        int topT = rect.height() - view.getHeight();
        
        Log.v("@@@@@@", "the statusbar Height is : " + topS);
        Log.v("@@@@@@", "the titleBar Height is : " + topT);

在我的手機上,均不行。

後:

public static int getStatusBarHeight(Context context){
	        Class<?> c = null;
	        Object obj = null;
	        Field field = null;
	        int x = 0, statusBarHeight = 0;
	        try {
	            c = Class.forName("com.android.internal.R$dimen");
	            obj = c.newInstance();
	            field = c.getField("status_bar_height");
	            x = Integer.parseInt(field.get(obj).toString());
	            statusBarHeight = context.getResources().getDimensionPixelSize(x); 
	            Log.v("@@@@@@", "the status bar height is : " + statusBarHeight);
	        } catch (Exception e1) {
	            e1.printStackTrace();
	        } 
	        return statusBarHeight;
	    }

經測試可行。




相關文章