Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

android - Get font scaling factor to calculate the fontsize

This question is related to Android App: how to read Font Size under Settings? I read the answer of CommonsWare which points to use Settings.System.FONT_SCALE. So I wrote this few lines:

float scale = -66.6f;
try {
    scale = android.provider.Settings.System.getFloat(getContentResolver(),
                                    android.provider.Settings.System.FONT_SCALE);
} catch(SettingNotFoundException e) {
    Log.e(getClass().getSimpleName(), "Error: ", e);
}
Toast.makeText(this, "scale=" + scale, Toast.LENGTH_LONG).show();

My problem is that I always get the SettingNotFoundException I'm using an Android 4.2.2 device. By the way I that code is in an onCreate callback of an Activity.

I also googled for that problem and found about 3 sites which uses the same code. Is some special permission required? I tried also the permission android.permission.WRITE_SETTINGS without success.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I just found in the source code of Settings.System this function:

/** @hide */
public static void getConfigurationForUser(ContentResolver cr,
                                       Configuration outConfig, int userHandle) {
    outConfig.fontScale = Settings.System.getFloatForUser(
        cr, FONT_SCALE, outConfig.fontScale, userHandle);
    if (outConfig.fontScale < 0) {
        outConfig.fontScale = 1;
    }
}

There is however the FONT_SCALE in usage so I checked for that Configuration class where the documentation points to getResources().getConfiguration(). So I counld fix my code by using:

float scale = getResources().getConfiguration().fontScale;

Since my question was about to calculate the correct font size in pixel here is the way I use it nowerdays in Kotlin:

val Number.dpInPx: Int
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP, toFloat(), Resources.getSystem().displayMetrics).toInt()

val Number.spInPx: Int
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_SP, toFloat(), Resources.getSystem().displayMetrics).toInt()

The usage is:

val textSize = 42.spInPx
val padding = 8.dpInPx

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...