Set buttons text to match the smallest text size in all of them Android

Osdon :

So i have a layout consisting of four Buttons each of them will carry a different text, by using the android:autoSizeTextType="uniform" and android:maxLines="1" the text will resize acordding to the buttons dimensions. The problem is that the buttons that have a small text appears to be huge compared to the other (text size), i want a way to resize all the texts to the smallest of them all in order to have a more cohesive design.

Image of the case

Ramees Thattarath :
  1. Add a global layout listener on root of the layout
  2. Inside the listener callback get text size of each Textview
  3. Get minimum among those text sizes
  4. turn off auto size feature using TextViewCompat
  5. Set text size to all Textviews (minimum obtained)

      root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            root.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            float txtSize1 = btn1.getTextSize();
            float txtSize2 = btn2.getTextSize();
            float minSize = Math.min(txtSize1, txtSize2);
            TextViewCompat.setAutoSizeTextTypeWithDefaults(btn1, TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
            TextViewCompat.setAutoSizeTextTypeWithDefaults(btn2, TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
    
            btn1.setTextSize(TypedValue.COMPLEX_UNIT_PX, minSize);
            btn2.setTextSize(TypedValue.COMPLEX_UNIT_PX, minSize);
    
        }
    });
    

If you have a dynamic text in any of the Textviews, then you should not remove the global layout listener. Also when text changes, set the AutoSizeTextType to uniform for all TextViews and call request layout on root, sample snippet after text change is below

   TextViewCompat.setAutoSizeTextTypeWithDefaults(btn1, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);

    TextViewCompat.setAutoSizeTextTypeWithDefaults(btn2, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);

    root.requestLayout();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=21788&siteId=1