如何在Android中通过编程方式找到TextView的文本区域(高度/宽度)

25

我有一个 EditText、一个 Button 和一个 TextView。当点击按钮时,textview 显示 edittext 中编写的文本。是否可以根据文本找到 textview 占用的大小。例如如果它有三个字符 "abc",现在的宽度是多少,如果它有 5 个字符如 "abcde",那么宽度是多少?

5个回答

81
Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
textPaint.getTextBounds(text,0,text.length(),bounds);
int height = bounds.height();
int width = bounds.width();
或者
textView.setText("bla");
textView.measure(0, 0);
textView.getMeasuredWidth();
textView.getMeasuredHeight();

1
这个功能非常好用 - 直到文本太长而无法适应一行并换行,添加第二行。由于getTextBounds()不知道一行文本的可用空间,所以计算出的高度将严重低估实际高度。 - xmjx

11
请尝试以下方法:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TextView edit = (TextView) findViewById(R.id.edit);
    edit.setTextSize(20);       
    edit.setText("Hello, world");       
    edit.measure(0, 0);
    int width = edit.getMeasuredWidth();
    Log.w("width", width.toString());
}

在获取宽度之前,您需要测量视图 / 标签 / 文本编辑器的宽度。 如果这不起作用,请告诉我。


两个答案都是正确的,你的和上面的那个...谢谢,它现在可以工作了。 - BST Kaal
我很高兴它能运行。 - Iosif
这会返回0,因为视图还没有被绘制。必须在view.post()中以Runnable执行才能获取尺寸。 - OzzyTheGiant

7
TextView txt = new TextView(mContext);
txt.setText("Some Text)";
int height = txt.getLineCount() *  txt.getLineHeight();
int width = txt.getWidth();

3
尝试这种方法,希望它能帮助您解决问题。
yourTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
   @Override
   public void onGlobalLayout() {
     int width = yourTextView.getMeasuredWidth();
     int height = yourTextView.getMeasuredHeight();

   }
});

你好 @M D,能否请您看一下这个链接:http://stackoverflow.com/questions/25196894/how-to-get-list-item-data-in-bindview-when-clicking-on-radiobutton-in-android - BST Kaal

2

请告诉我您想要什么单位的宽度?

TextView 的方法getWidth()可以返回您的视图的宽度,以像素为单位。

TextView textView = (TextView)findViewById(R.id.textview);
textView.getWidth(); //width of your view, in pixels 

我想根据文本找到宽度。 - BST Kaal

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