关闭

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

标签: Android获取控件宽度获取控件高度
2445人阅读 评论(0) 收藏 举报
分类:

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
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:19255次
    • 积分:430
    • 等级:
    • 排名:千里之外
    • 原创:23篇
    • 转载:6篇
    • 译文:0篇
    • 评论:11条
    文章分类
    最新评论