获取控件(布局或View)宽度或高度的方法

1.onCreate()/onCreateView()中是无法通过view.getHight()/getWidth()反法获取到控件的高度或宽度

因为此时控件的onMeasure()方法没有调用,本身还不知道自己的属性

2.解决方法(推荐两种)

1.设置addOnPreDrawListener()回调方法

        final ViewTreeObserver vto = view.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int width = view.getWidth();
                int measuredWidth = view.getMeasuredWidth();
                ViewGroup.LayoutParams params = view.getLayoutParams();
                int  paramWidth = params.width;
                show.append("\n\n" + "width:" + view.getHeight() + "," + view.getWidth() +
                        "\n" + "measuredWidth:" + measuredWidth + "," + view.getMeasuredHeight() +
                        "\n" + "paramWidth:" + paramWidth);
            }
        });

其中veiw是你想测量的布局或控件,从结果中可以发现getWidth()和getMeasureWidth()方法是可以获取到控件的宽度,区别在getWidth获取的是屏幕中能看到的宽度,getMeasureWidth()是控件本身的自身宽度,还不懂可以看这里:http://blog.sina.com.cn/s/blog_6e519585010152s5.html(借鉴下,感谢您),通过LayoutParams在这里是获取到-1,所以不行,之后如果你想动态设置控件的宽或高可以通过以下方法来设置
ViewGroup.LayoutParams params = view.getLayoutParams();
                params.height = measuredWidth;
                view.setLayoutParams(params);
需要注意:
  1. LayoutParams是你需要设置的控件的父布局的LayoutParams.
  2. view.getViewTreeObserver().removeOnGlobalLayoutListe(this);需要调用,否则会调用多次
 
   

2.设置addOnPreDrawListener()回调

        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {

            @Override
            public boolean onPreDraw() {
                int height = view.getMeasuredHeight();
                int width = view.getMeasuredWidth();
                view.getViewTreeObserver().removeOnPreDrawListener(this);
                int width = view.getWidth();
                int measuredWidth = view.getMeasuredWidth();

                int paramWidth = params.width;
               // show.append("\n\n" + "width:" + view.getHeight() + "," + view.getWidth() +
                 //       "\n" + "measuredWidth:" + measuredWidth + "," + view.getMeasuredHeight() +
                   //     "\n" + "paramWidth:" + paramWidth);
                //ViewGroup.LayoutParams params = view.getLayoutParams();
                //params.height = measuredWidth;
                //view.setLayoutParams(params);
                return true;
            }
        });


你可能感兴趣的:(android)