从"设置"中读取字体大小

rek*_*ire 15 settings android android-permissions

这个问题几乎是一个Android应用程序:如何读取设置下的字体大小?我读了CommonsWare的答案,指出要使用Settings.System.FONT_SCALE.所以我写了几行:

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();
Run Code Online (Sandbox Code Playgroud)

我的问题是我总是得到SettingNotFoundException我正在使用Android 4.2.2设备.顺便说一句,我的代码是在一个onCreate回调中Activity.

我也搜索了该问题并发现了大约3个使用相同代码的网站.是否需要一些特殊许可?我也尝试了许可android.permission.WRITE_SETTINGS但没有成功.

rek*_*ire 36

我刚刚在Settings.System这个函数的源代码中找到:

/** @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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,FONT_SCALE在使用中,我检查Configuration了文档指向的那个类getResources().getConfiguration().所以我通过使用以下方法来修复我的代码:

float scale = getResources().getConfiguration().fontScale;
Run Code Online (Sandbox Code Playgroud)


Har*_*nia 6

您可以根据字体比例设置系统字体。

示例:对于大字体比例为 2.0,您可以设置如下。

Configuration config = new Configuration();
config.fontScale = 2.0f;
getResources().getConfiguration().setTo(config);
Run Code Online (Sandbox Code Playgroud)