Home > Mobile >  Autosizing button text programmatically
Autosizing button text programmatically

Time:08-11

I'm creating buttons programmatically and the text is slightly cut-off. I trying to autosize the text-size but I've only found how to do so in XML:

app:autoSizeTextType="uniform"

but have to to do programmatically and can't figure out how to do so with a button and not a TextView. I tried the following line:

letter.setAutoSizeTextTypeUniformWithConfiguration(10, 100,2, TypedValue.COMPLEX_UNIT_SP);

but it doesn't do anything.

This is how my buttons are created, the width depends on the screen width:

Button letter = new Button(context);
LinearLayout.LayoutParams btnlp = new LinearLayout.LayoutParams(dpWidth/10-2, LinearLayout.LayoutParams.WRAP_CONTENT);
            btnlp.setMargins(1,15,0, 0);

CodePudding user response:

Using Sample xml. You don't need to program.

android:autoSizeTextType="uniform"
android:autoSizeMinTextSize="12sp"
android:autoSizeMaxTextSize="100sp"
android:autoSizeStepGranularity="2sp"

CodePudding user response:

there is a related method setAutoSizeTextTypeWithDefaults, but is available starting API26, so I would advice you to use more universal TextViewCompat

TextViewCompat.setAutoSizeTextTypeWithDefaults(textView, 
    TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM);
  • Related