[英]Get exact width of a textview in pixel programmatically (Android)
Using android, does anybody know how to get the exact width of a textview, in pixel, before it's displayed on the screen ? 使用android,有人知道在屏幕上显示textview之前如何获得它的确切宽度(以像素为单位)吗? (programmatically) I've search a lot on the internet but I didn't found anything working.
(以编程方式)我在互联网上进行了大量搜索,但没有发现任何有效的方法。
Thank you 谢谢
Links of the post I tried : 我尝试过的帖子的链接:
I think that you should use OnGlobalLayoutListener
which is usually used to find out the height and the width of views before they are drawn. 我认为您应该使用
OnGlobalLayoutListener
,通常用于在绘制视图之前查明视图的高度和宽度。
For example, 例如,
yourTextView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
yourTextView.getWidth();
}
});
It was better that you had sent some code. 最好发送一些代码。 Then we could help you more.
然后,我们可以为您提供更多帮助。 But I think that you may use these methods:
但我认为您可以使用以下方法:
yourText.measure(0, 0);
And then these codes: 然后这些代码:
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
try this. 尝试这个。
textView.setText("your text");
textView.measure(0, 0);
textView.getMeasuredWidth();
textView.getMeasuredHeight();
As Nargess said you'd better use methods of measuring view's width and height, like code below: 正如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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.