在Android中如何获取设置为Wrap_Content的Textview的宽度?

9

我正在尝试向一个TextView添加文本,该TextView的宽度已设置为Wrap_content。我想要获取这个TextView的宽度,但是无论什么情况下都显示为0。如何在将文本设置到TextView后获取其宽度。

代码如下:

        LinearLayout ll= new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        TextView tv = new TextView(this);
        tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        ll.addView(tv);
        tv.setText("Hello 1234567890-0987654321qwertyuio787888888888888888888888888888888888888888888888888");
        System.out.println("The width is == "+tv.getWidth());// result is 0
        this.setContentView(ll);

请提供建议。 提前感谢你。
8个回答

11

只有在完成布局过程后,具有动态宽度/高度的视图才能获得其正确的大小(http://developer.android.com/reference/android/view/View.html#Layout)。
您可以将OnLayoutChangeListener添加到TextView中,在那里获取其大小:

tv.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
           public void onLayoutChange(View v, int left, int top, int right, int bottom, 
                                      int oldLeft, int oldTop, int oldRight, int oldBottom) {
                        final int width = right - left;
                        System.out.println("The width is == " + width);                
    });

它在API 8及以上的版本中有什么等效物? - newton_guima
你可以继承TextView并重写onLayout()方法。在其中调用super.onLayout(),并保存TextView的宽度。这对于任何API级别都应该有效。 - Const
该类需要API级别11(当前最低级别为8):android.view.View.OnLayoutChangeListener。 - Bhavin Chauhan

3
在布局完全构建之前,您无法获取动态尺寸的视图宽度。这意味着您无法在onCreate()中获取它。一种方法是创建一个继承自TextView并覆盖onSizeChanged()方法的类。

1

你是什么时候调用它的?它已经被绘制到屏幕上了吗?

听起来你太早调用了getWidth()

你也可以看一下这个问题


0

你好,使用这个方法:

textview.post(new Runnable() {
    @Override
    public void run() {
        int width = textview.getWidth();
        int height = textview.getHeight();
        textview.setText( String.valueOf( width +","+ height ));
    }

});

来源:https://gist.github.com/omorandi/59e8b06a6e81d4b8364f


感谢您提供这段代码片段,它可能会提供一些有限的、即时的帮助。通过展示为什么这是一个好的解决方案,一个适当的解释将极大地提高其长期价值,并使其对未来读者具有其他类似问题更有用。请[编辑]您的答案以添加一些解释,包括您所做出的假设。 - Mogsdad

0

这对我有效:

RelativeLayout.LayoutParams mTextViewLayoutParams = (RelativeLayout.LayoutParams) mTextView.getLayoutParams();
mTextView.setText(R.string.text);
mTextView.measure(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
int width = mShareTip.getMeasuredWidth();
//use the width to do what you want
mShareTip.setLayoutParams(mShareTipLayoutParams);

0

您可以使用该库来安排在视图完全绘制后执行宽度计算任务的正确时间

https://github.com/Mohamed-Fadel/MainThreadScheduler

使用示例:

MainThreadScheduler.scheduleWhenIdle(new Runnable() {
       @Override
       public void run() {
           int width = textview.getWidth();
           int height = textview.getHeight();
           textview.setText( String.valueOf( width +","+ height ));
       }
   });

0

你应该使用这个:

textView.getMeasuredWidth();


0

你可以尝试这个:

textView.measure(0,0);
int width = textView.getMeasuredWidth();

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