Android获得statusBar高度

在画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;
	    }

经测试可行。




你可能感兴趣的:(Android获得statusBar高度)