How to auto size textview dynamically according to the length of the text in android?

前端 未结 7 791
不思量自难忘°
不思量自难忘° 2021-02-04 07:07

I am taking data of variable sizes from the server and setting to a textView and i wanted the textview to resize according to the length of the text set.

It is given in

相关标签:
7条回答
  • 2021-02-04 07:36

    Here's one way to do it, using the support library:

    <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:breakStrategy="balanced" 
            android:gravity="center_horizontal"
            android:maxLines="1"
            android:text="Hello world" 
            android:textSize="300sp" 
            app:autoSizeTextType="uniform"
            tools:targetApi="o"/>
    

    The android:breakStrategy allows making the text go to the next line nicely, instead of the default behavior which might break the words.

    In gradle, use this:

    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'com.google.android.material:material:1.0.0-beta01'
    

    Or this:

    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    

    Note that it's recommended to set layout restrictions on the TextView (width and/or height), to make sure you will get it right. All depends on your use case.

    0 讨论(0)
提交回复
热议问题