【问题标题】:Android get textview width and height before the setting text and renderingAndroid在设置文本和渲染之前获取textview的宽度和高度
【发布时间】:2016-08-05 16:57:34
【问题描述】:

我正在尝试获取设置文本的 textview 的宽度。这是我正在使用的代码:

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();
}

但是这个方法返回更大的宽度。示例:

  1. 我需要在 textview 中设置值“6978”
  2. 这个方法是计算width = 46(顺便返回值是dp还是sp?我是在dp中设置的,导致px这个值不够。)
  3. 如果我将 textview 的宽度设置为 46 dp 或 sp,TextView 将有额外的位置

我需要得到与 width="wrap_content" 一致的宽度值

TextView 大小和字体有默认值。

【问题讨论】:

    标签: android textview width


    【解决方案1】:

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

     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;
        }
    

    【讨论】:

      【解决方案2】:

      我知道你的请求过了一会儿,但你是在 OnGlobalLayoutListener 中运行检查吗?

      如果没有,那么视图将不会完全绘制在屏幕上,并且您将没有可用的尺寸。

      在 onGlobalLayout() 中可以调用measuredWidth 和measuredHeight。

      我希望这会有所帮助,如果不是你,那么是其他人。

      【讨论】: