【问题标题】:getHeight() on a TextView initialised in code在代码中初始化的 TextView 上的 getHeight()
【发布时间】:2014-01-23 22:04:11
【问题描述】:

我已经在代码中初始化了一个TextView(也就是说,没有从布局中初始化它)

TextView   v   =    new TextView(getApplicationContext());

然后我设置文本

v.setText("Foo");

然后我尝试获取这个TextView的高度

int i = v.getHeight();

这是给 0。

请指教

【问题讨论】:

  • TextView v = new TextView(ActivityName.this)); 和 v 应该添加到根布局或活动中。并阅读stackoverflow.com/questions/7298731/… 尽管您的v.getHeight() 是一个不同的问题
  • 您刚刚创建了对象,测量和布局是否通过了?在那之前你怎么能得到身高。将其添加到某个布局,然后调用 v.requestLayout(),然后调用 layout.post(new Runnable() { public void run() {mHeight = v.getHeight}};) 发布的可运行将在测量/布局传递后运行.希望对您有所帮助。
  • 其实我的帖子里少了一条信息......我把视图添加到表格行,然后在TextView上调用getHeight()

标签: java android android-widget textview


【解决方案1】:

您的 TextView 可能尚未测量。 使用 ViewTreeObserver,您可以在 TextView 渲染时收到通知,然后您可以获得它的高度:

ViewTreeObserver vto = v.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

@Override
public void onGlobalLayout() {
if (v != null && getActivity() != null) {
    ViewTreeObserver obs = v.getViewTreeObserver();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        obs.removeOnGlobalLayoutListener(this);
    } else {
        obs.removeGlobalOnLayoutListener(this);
    }
    int i = v.getHeight();

    }
 }
});

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2011-12-19
  • 1970-01-01
  • 2013-01-04
  • 2017-05-25
相关资源
最近更新 更多