获取控件(布局或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;
            }
        });


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值