Question

There's a font setting in Android system settings. I've tested my layouts with all the options from default Normal up to Huge, but it didn't occur to me someone would use Small. Turns out, someone does.

My layouts use styles, and styles have some dimensions constrained to certain sp or dp values. It took a lot of trial and error to balance the values for all the screen and font sizes, and I would really like not having to tweak it all over again from scratch. Is there a way for my app to ignore the font size setting? Is there a way to say to Android that I don't want the app to be affected by options smaller than Normal?

Was it helpful?

Solution

Following is a little dirty, but worked on Nexus 5 (Android 4.4.2):

AndroidManifest.xml

<uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="MainActivity"
        android:label="@string/app_name"
        android:configChanges="fontScale" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

MainActivity.java

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Make sure to do this before setContentView()
        Configuration currentConfig = getResources().getConfiguration();
        if (currentConfig.fontScale < 1.0f) {
            currentConfig.fontScale = 1.0f;
            getResources().updateConfiguration(currentConfig, null);
        }

        setContentView(R.layout.activity_main);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if (newConfig.fontScale < 1.0f) {
            newConfig.fontScale = 1.0f;
        }
        getResources().updateConfiguration(newConfig, null);

        // Restart to apply the new changes
        AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP,
                Calendar.getInstance().getTimeInMillis() + 1000, // one second
                PendingIntent.getActivity(this, 0, getIntent(), PendingIntent.FLAG_ONE_SHOT
                        | PendingIntent.FLAG_CANCEL_CURRENT));
        finish();
    }
}

Hope this helps.

Please let me know if there is any need for explanation of the above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top