TextView text is compressed to the specified width.

I have a textview field in my activity. Its font size is 16. Its text is specified through code. Suppose that if I have large text, it should reduce this data (i.e. the font size decreases) instead of going to the next line. How can i do this?

<TextView android:id="@+id/textView" android:layout_width="400dp" android:layout_height="wrap_content" android:text="" android:textSize="16sp" />
+3
source share
3 answers

I received it using the following method, which I created as per my requirement.

private void autoScaleTextViewTextToHeight(TextView tv)
    {
        String s = tv.getText().toString();
        float currentWidth = tv.getPaint().measureText(s);

        float phoneDensity = this.getResources().getDisplayMetrics().density;

        while(currentWidth > (REQUIRED_WIDTH * phoneDensity)) {         
            tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, tv.getTextSize() - 1.0f); 
            currentWidth = tv.getPaint().measureText(s);
        }
    }
+9
source

The following method accepts the TextView as parameter and adjusts the font size according to the width of the given TextView

private void adjustTextSize(TextView tv) {

    float size = tv.getPaint().getTextSize();
    TextPaint textPaint = tv.getPaint();
    float stringWidth = textPaint.measureText(tv.getText().toString());
    int textViewWidth = tv.getWidth();
    if(textViewWidth > stringWidth) {

        float percent = (textViewWidth / stringWidth);
        textPaint.setTextSize(size*percent);
    }
}

Hope this helps.

+1
source

there is no good way. what you can do is calculate the size of the text that you are going to place in this TextView and resize it until it is in the target area. to calculate the size, use Paint.getTextBounds ().

I did a very similar drawing on canvas. requries is a loop that reduces the font size until there is a suitable size.

0
source

Source: https://habr.com/ru/post/1795395/


All Articles