gpt4 book ai didi

android - 获取字体缩放因子以计算字体大小

转载 作者:可可西里 更新时间:2023-11-01 19:09:46 26 4
gpt4 key购买 nike

这个问题与Android App: how to read Font Size under Settings?有关我看了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();

我的问题是我总是得到 SettingNotFoundException 我使用的是 Android 4.2.2 设备。顺便说一句,我的代码在 ActivityonCreate 回调中。

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

最佳答案

刚刚在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;
}
}

然而,FONT_SCALE 正在使用中,所以我检查了它 Configuration文档指向 getResources().getConfiguration() 的类。所以我可以使用以下方法修复我的代码:

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

因为我的问题是要计算正确的像素字体大小,所以我现在在 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()

用法是:

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

关于android - 获取字体缩放因子以计算字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16544931/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com