【问题标题】:Get height and width of a textview set using layout weights?使用布局权重获取文本视图集的高度和宽度?
【发布时间】:2016-01-13 05:56:43
【问题描述】:

我已经使用布局权重在线性布局中设置了 TextView。

   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;

【问题讨论】:

标签: android android-layout android-linearlayout


【解决方案1】:

使用

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
        }
    });

【讨论】:

  • 这是最有帮助的。谢谢!希望有更短的方法。
  • 是的,一旦我在这个问题上徘徊了将近 5-6 个小时,然后得到了这个解决方案
  • 使用stackoverflow.com/a/16190337/2437655 removeGlobalOnLayoutListener 弃用
【解决方案2】:

尝试关注

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

【讨论】:

  • 不起作用。返回高度为 -1,重量为 2147483647。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-06
  • 2016-04-18
  • 2013-06-01
相关资源
最近更新 更多