Android - 获取控件(包括状态栏与标题栏)宽高

        //------------------------------------------------方法一
        int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        imageView.measure(w, h);
        int height =imageView.getMeasuredHeight();
        int width =imageView.getMeasuredWidth();
        textView.append("\n"+height+","+width);
        
        
        

        //-----------------------------------------------方法二
        ViewTreeObserver vto = imageView.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                int height = imageView.getMeasuredHeight();
                int width = imageView.getMeasuredWidth();
                textView.append("\n"+height+","+width);
                return true;
            }
        });
        //-----------------------------------------------方法三   
        ViewTreeObserver vto2 = imageView.getViewTreeObserver();  
        vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override  
            public void onGlobalLayout() {
                imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);  
                textView.append("\n\n"+imageView.getHeight()+","+imageView.getWidth());
            }  
        });  

方法一: 比其他的两个方法多了一次计算,也就是多调用了一次onMeasure()方法,该方法虽然看上去简单,但是如果要目标控件计算耗时比较大的话(如listView等),不建议使用.

方法二,它的回调方法会调用很多次,并且滑动TextView的时候任然会调用,所以不建议使用.

方法三,比较合适.

当然,实际应用的时候需要根据实际情况而定.

from:http://blog.csdn.net/johnny901114/article/details/7839512

 

获取状态条高度

在源码程序中代码:

height= getResources().getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);

通过SDK反射获取代码:

class c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
int y = getResources().getDimensionPixelSize(x);

标题栏的高度:

240x320的高度为20px

320x480的高度为25px

480x800的高度为38px

@Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        Rect rect = new Rect();
        Window win = getWindow();
        win.getDecorView().getWindowVisibleDisplayFrame(rect);
        //状态栏高度
        int statusBarHeight = rect.top; 
        //状态栏与标题栏高度总和
        int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop(); 
        int titleBarHeight = contentViewTop - statusBarHeight; 
        Log.d("状态栏高度:" + statusBarHeight);
        Log.d("标题栏高度:" + titleBarHeight);
    }

 

posted @ 2013-04-11 10:29  Android Walker  阅读(1271)  评论(0编辑  收藏  举报