Search code examples
androidtextview

How to autoSizeTextType to unifrom programatically?


It's possible to do this

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:autoSizeTextType="uniform"
    android:maxLines="1" />

But property autoSizeTextType is able only for API LEVEL >= 26, and Android Studio shows annoying warning about that.

In order to get rid of that, I want to do that programmatically, but there are 3 methods:

textView.setAutoSizeTextTypeUniformWithPresetSizes(...)
textView.setAutoSizeTextTypeUniformWithConfiguration(...)

These two require configuration, but I want to be a default configuration, the same as android:autoSizeTextType="uniform".

textView.setAutoSizeTextTypeWithDefaults(TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM);

This says:

AppCompatTextView.setAutoSizeTextTypeWithDefaults can only be called from within the same library group (groupId=com.android.support).

PS: I wrap up the code into:

if(android.os.Build.VERSION.SDK_INT= > 26) {...}

Solution

  • You can use TextViewCompat class for avoid the Library Restriction error. Like,

    TextViewCompat.setAutoSizeTextTypeWithDefaults(textView,TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);