How to scale/resize text to fit a TextView? How to scale/resize text to fit a TextView? android android

How to scale/resize text to fit a TextView?


The AutofitTextView library from MavenCentral handles this nicely. The source hosted on Github(1k+ stars) at https://github.com/grantland/android-autofittextview

Add the following to your app/build.gradle

repositories {    mavenCentral()}dependencies {    implementation 'me.grantland:autofittextview:0.2.+'}

Enable any View extending TextView in code:

AutofitHelper.create(textView);

Enable any View extending TextView in XML:

<me.grantland.widget.AutofitLayout    android:layout_width="match_parent"    android:layout_height="wrap_content"    >    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:singleLine="true"        /></me.grantland.widget.AutofitLayout>

Use the built in Widget in code or XML:

<me.grantland.widget.AutofitTextView    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:singleLine="true"    />


New since Android O:

https://developer.android.com/preview/features/autosizing-textview.html

<TextView  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:autoSizeTextType="uniform"  android:autoSizeMinTextSize="12sp"  android:autoSizeMaxTextSize="100sp"  android:autoSizeStepGranularity="2sp"/>


I have played with this for quite some time, trying to get my font sizes correct on a wide variety of 7" tablets (kindle fire, Nexus7, and some inexpensive ones in China with low-res screens) and devices.

The approach that finally worked for me is as follows. The "32" is an arbitrary factor that basically gives about 70+ characters across a 7" tablet horizontal line, which is a font size I was looking for. Adjust accordingly.

textView.setTextSize(getFontSize(activity));public static int getFontSize (Activity activity) {     DisplayMetrics dMetrics = new DisplayMetrics();    activity.getWindowManager().getDefaultDisplay().getMetrics(dMetrics);    // lets try to get them back a font size realtive to the pixel width of the screen    final float WIDE = activity.getResources().getDisplayMetrics().widthPixels;    int valueWide = (int)(WIDE / 32.0f / (dMetrics.scaledDensity));    return valueWide;}