4

I need to change the font size of my application at runtime. I referred the following SO post where they speak about applying font size via styles.xml and applying it. I think it's applicable only for a particular element (like TextView or layout) but is it possible to apply the font size at application level and is it possible to set it programmatically?

Andrii Artamonov
  • 622
  • 8
  • 15
Tom Taylor
  • 3,344
  • 2
  • 38
  • 63
  • Does this answer your question? [How to change the Font Size in a whole Application programmatically, Android?](https://stackoverflow.com/questions/12704216/how-to-change-the-font-size-in-a-whole-application-programmatically-android) – Mohamed Nageh Jan 19 '20 at 14:55

2 Answers2

4

Take your text view TextView textView and apply setTextSize(size)

textView.setTextSize(20);

Note that size is in pixels, not dp as in styles.xml layout

TheD3t0
  • 135
  • 4
2

Yes, setting text size is :

textView.setTextSize(20)// text size

added few more things here :)

1.If you want to set as DP

textView.setTextSize(coverPixelToDP(20));
    
private int coverPixelToDP (int dps) {
    final float scale = this.getResources().getDisplayMetrics().density;
    return (int) (dps * scale);
}

2.If you want to adjust font size automatically to fit boundaries use,

setAutoSizeTextTypeUniformWithConfiguration(int autoSizeMinTextSize, int autoSizeMaxTextSize, int autoSizeStepGranularity, int unit)

JAVA Version

TextView textView = new TextView(this);
textView.setText("Adjust font size for dynamic text");
//only works when width = 'match_parent', and give height
LinearLayout.LayoutParams p1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 500); 
           
textView.setLayoutParams(p1);
textView.setAutoSizeTextTypeUniformWithConfiguration(8, 15, 1, TypedValue.COMPLEX_UNIT_DIP); 

XML Version (Programatically)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <TextView
      android:layout_width="match_parent" // make sure it is match_parent
      android:layout_height="500dp" //make sure you give height 
      app:autoSizeTextType="uniform"
      app:autoSizeMinTextSize="12sp"
      app:autoSizeMaxTextSize="100sp"
      app:autoSizeStepGranularity="2sp" />

</LinearLayout>
Tom Taylor
  • 3,344
  • 2
  • 38
  • 63
Energy
  • 940
  • 13
  • 20