【发布时间】:2014-08-13 02:47:32
【问题描述】:
我有一个EditText、一个Button 和一个TextView。单击按钮时,textview 会显示用 edittext 编写的文本。是否可以根据文本找到占用的文本视图的大小。即如果它有三个字符“abc”,那么现在宽度是多少,如果它有五个字符,比如“abcde”,那么宽度是多少?
【问题讨论】:
标签: android android-layout textview layoutparams
我有一个EditText、一个Button 和一个TextView。单击按钮时,textview 会显示用 edittext 编写的文本。是否可以根据文本找到占用的文本视图的大小。即如果它有三个字符“abc”,那么现在宽度是多少,如果它有五个字符,比如“abcde”,那么宽度是多少?
【问题讨论】:
标签: android android-layout textview layoutparams
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();
【讨论】:
请试试这个:
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());
}
在获得宽度之前,您必须测量视图/标签/文本编辑。 如果这不起作用,请告诉我。
【讨论】:
view.post() 的 Runnable 中完成才能获得尺寸
TextView txt = new TextView(mContext);
txt.setText("Some Text)";
int height = txt.getLineCount() * txt.getLineHeight();
int width = txt.getWidth();
【讨论】:
试试这个方法,希望能帮助你解决问题。
yourTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int width = yourTextView.getMeasuredWidth();
int height = yourTextView.getMeasuredHeight();
}
});
【讨论】:
请告诉我宽度???你要吗?
TextView 方法 getWidth() 为您提供视图的宽度,以像素为单位
TextView textView = (TextView)findViewById(R.id.textview);
textView.getWidth(); //width of your view, in pixels
【讨论】: