使用布局权重设置的TextView,如何获取其高度和宽度?

3

我在线性布局中使用了layout weights来设置TextViews。

   linearLayout.setWeightSum(7f);

   for(int i=0;i<7;i++){
     TextView tv= new TextView(this);
     tv.setLayoutParams(new LinearLayout.LayoutParams(
                        LayoutParams.MATCH_PARENT, 0, 1f));
     tv.setText("sometext");
     linearLayout.addView(tv);
   }

当布局绘制完成后,我如何获取这些TextView的宽度和高度?

tv.getWidth() 和 tv.getHeight() 返回0;


可能是View的getWidth()和getHeight()返回0的重复问题。 - Dan
如果其他人遇到了这个问题,并且想要更快地解决它,可以在此答案中找到几个选项。 - Dan
2个回答

10

使用

getViewTreeObserver

作为

 yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // Ensure you call it only once :
            yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

            // get size of view here
        }
    });

这非常有帮助。谢谢!但希望还能有更短的方法。 - nette
是的,我曾经为这个问题苦恼了将近5-6个小时,然后找到了这个解决方案。 - Amarjit
使用https://dev59.com/LWQo5IYBdhLWcg3wR9nD#16190337来解决removeGlobalOnLayoutListener过时的问题 - Shubham AgaRwal

-1

请尝试以下内容

TextView mLblDesc=(TextView)findViewById(R.id.mLblDesc);
        mLblDesc.getMaxHeight();
        mLblDesc.getMaxWidth();

不起作用。将高度返回为-1,将重量返回为2147483647。 - nette

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接