How to Measure TextView Height Based on Device Width and Font Size?

后端 未结 3 1713
花落未央
花落未央 2020-11-29 05:49

I am looking for method in Android that will take a input (text, text_font_size, device_width) and based on these calculations it will return how much height will required t

3条回答
  •  执笔经年
    2020-11-29 06:42

    public static int getHeight(Context context, String text, int textSize, int deviceWidth) {
        TextView textView = new TextView(context);
        textView.setText(text);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        int widthMeasureSpec = MeasureSpec.makeMeasureSpec(deviceWidth, MeasureSpec.AT_MOST);
        int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        textView.measure(widthMeasureSpec, heightMeasureSpec);
        return textView.getMeasuredHeight();
    }
    

    If textSize is not given in pixels, change the first paramter of setTextSize().

提交回复
热议问题