2013-04-15 61 views
5

我正在尝试向textview添加文本,我已将宽度设置为Wrap_content。我试图获得这个textview的宽度。但在所有情况下它都显示为0。如何在设置文本后获得文本视图的宽度。在Android中如何获取设置为Wrap_Content的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); 

请建议。 在此先感谢。

回答

1

你打电话给什么时候?它已经被吸引到屏幕上吗?

听起来好像你打电话getWidth()太早。

您还可以采取look at this question

2

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

6

只有在布局过程完成后(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);     
    }); 
+0

什么其等效为API 8及以上? –

+0

您可以继承TextView并覆盖onLayout()。从它调用super.onLayout()并保存TextView的宽度。这应该适用于任何API级别。 – Const

+0

类需要API级别11(当前最小值为8):android.view.View.OnLayoutChangeListener –

-1

你应该使用这样的:

textView.getMeasuredWidth();

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

你可以试试这个:

textView.measure(0,0); 
int width = textView.getMeasuredWidth(); 
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

+0

感谢您使用此代码段,它可能会提供一些有限的即时帮助。一个[正确的解释将大大提高其长期价值](/ meta.stackexchange.com/q/114762/206345)通过显示_why_这是一个很好的解决方案,并将使它对未来的读者更有用其他类似的问题。请[编辑]你的答案以添加一些解释,包括你所做的假设。 – Mogsdad

相关问题