Android在设置文本和渲染之前获取文本视图的宽度和高度
我正在尝试获取设置文本的文本视图的宽度。以下是我正在使用的代码:Android在设置文本和渲染之前获取文本视图的宽度和高度,android,textview,width,Android,Textview,Width,我正在尝试获取设置文本的文本视图的宽度。以下是我正在使用的代码: public int getTextViewEffectedWidth(TextView textView, String content){ Rect bounds = new Rect(); Paint paint = textView.getPaint(); paint.getTextBounds(content, 0, content.length()
public int getTextViewEffectedWidth(TextView textView, String content){
Rect bounds = new Rect();
Paint paint = textView.getPaint();
paint.getTextBounds(content, 0, content.length(), bounds);
return bounds.width();
}
但是这个方法返回更大的宽度。例如:
文本视图大小和字体有默认值。试试这个,你会得到像素值
int width=convertToPixel(textView.getWidth());
int height=convertToPixel(textView.getHeight());
private int convertToPixel(int n) {
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, n, r.getDisplayMetrics());
return (int) px;
}
试试这个,你会得到像素值
int width=convertToPixel(textView.getWidth());
int height=convertToPixel(textView.getHeight());
private int convertToPixel(int n) {
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, n, r.getDisplayMetrics());
return (int) px;
}
我知道你的请求过了一段时间,但是你是否在OnGlobalYoutListener中运行检查 如果没有,那么视图将不会完全绘制在屏幕上,并且您将没有可用的尺寸 在onGlobalLayout()中,可以调用measuredWidth和measuredHeight
我希望这能有所帮助,如果不是你,那么是其他人。我知道在你的请求之后还有一段时间,但是你是否在OnGlobalYoutListener中运行检查 如果没有,那么视图将不会完全绘制在屏幕上,并且您将没有可用的尺寸 在onGlobalLayout()中,可以调用measuredWidth和measuredHeight 我希望这对你有帮助,如果不是你,还有其他人