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();
}
但是这个方法返回更大的宽度。例如:

  • 我需要设置文本视图值“6978”
  • 该方法的计算宽度为46(顺便说一下,dp中的返回值或dp中的sp?I设置,导致px中的该值不够。)
  • 如果我设置textview的宽度为46 dp或sp,textview将有额外的位置
  • 我需要获得与width=“wrap\u content”一致的宽度值


    文本视图大小和字体有默认值。

    试试这个,你会得到像素值

     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

    我希望这对你有帮助,如果不是你,还有其他人