以编程方式获取以像素为单位的文本视图的精确宽度 (Android)
Get exact width of a textview in pixel programmatically (Android)
使用 android,有人知道如何在文本视图显示在屏幕上之前获取它的确切宽度(以像素为单位)吗? (以编程方式)
我在互联网上搜索了很多,但没有找到任何有效的方法。
谢谢
post 我试过的链接:
With a Paint
With measure
With density
试试这个。
textView.setText("your text");
textView.measure(0, 0);
textView.getMeasuredWidth();
textView.getMeasuredHeight();
最好您发送了一些代码。那么我们可以为您提供更多帮助。
但我认为你可以使用这些方法:
yourText.measure(0, 0);
然后是这些代码:
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
正如Nargess所说,你最好使用测量视图宽度和高度的方法,如下面的代码:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
view.measure(size.x, size.y);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
我认为你应该使用 OnGlobalLayoutListener
,它通常用于在绘制视图之前找出视图的高度和宽度。
例如,
yourTextView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
yourTextView.getWidth();
}
});
使用 android,有人知道如何在文本视图显示在屏幕上之前获取它的确切宽度(以像素为单位)吗? (以编程方式) 我在互联网上搜索了很多,但没有找到任何有效的方法。
谢谢
post 我试过的链接:
- With a Paint
- With measure
- With density
试试这个。
textView.setText("your text");
textView.measure(0, 0);
textView.getMeasuredWidth();
textView.getMeasuredHeight();
最好您发送了一些代码。那么我们可以为您提供更多帮助。 但我认为你可以使用这些方法:
yourText.measure(0, 0);
然后是这些代码:
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
正如Nargess所说,你最好使用测量视图宽度和高度的方法,如下面的代码:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
view.measure(size.x, size.y);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
我认为你应该使用 OnGlobalLayoutListener
,它通常用于在绘制视图之前找出视图的高度和宽度。
例如,
yourTextView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
yourTextView.getWidth();
}
});