现在的位置: 首页 > 综合 > 正文

Android获取状态栏、标题栏、ActionBar以及屏幕的高度

2014年06月03日 ⁄ 综合 ⁄ 共 1324字 ⁄ 字号 评论关闭

一、屏幕高度和宽度获取方法

int screenWidth,screenHeight;  
WindowManager windowManager = getWindowManager();  
Display display = windowManager.getDefaultDisplay();  
screenWidth = display.getWidth();  
screenHeight = display.getHeight();

另外一种

DisplayMetrics dm = new DisplayMetrics();     
getWindowManager().getDefaultDisplay().getMetrics(dm);     
int screenWidth = dm.widthPixels;     
int screenHeight = dm.heightPixels; 

二、状态栏高度获取方法

Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;

上面这种方法基本上是可以的,但是下面这种方法更牛逼

private int getStatusBarHeight() {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 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());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            Log.d(TAG, "get status bar height fail");
            e1.printStackTrace();
            return 75;
        }
    }

三、获取标题栏的高度

int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面状态栏的高度
int titleBarHeight = contentTop - statusBarHeight;

四、获取ActionBar高度

int actionBarHeight = getActionBar().getHeight();

注意 :如果是在Activity的onCreate函数中就开始使用,需要将其放入Runnable中调用,因为这个时候控件的高度可能还没有确定。

View root;
。。。。
root.post(new Runnable() {
            @Override
            public void run() {
                //To change body of implemented methods use File | Settings | File Templates.
                getActivityContentHeight();
            }
        });

抱歉!评论已关闭.