我最近完成了我的安卓应用程序开发。我在所有文本大小上使用了sp(缩放像素)。问题是当我调整系统字体大小时,我的应用程序的字体大小也会改变。我可以使用dp(设备独立像素),但这将需要太长时间来维护我的应用程序。
我参考了这里的文本大小。
有没有办法防止系统字体大小的变化影响到我的应用程序?
我最近完成了我的安卓应用程序开发。我在所有文本大小上使用了sp(缩放像素)。问题是当我调整系统字体大小时,我的应用程序的字体大小也会改变。我可以使用dp(设备独立像素),但这将需要太长时间来维护我的应用程序。
我参考了这里的文本大小。
有没有办法防止系统字体大小的变化影响到我的应用程序?
我认为使用dp
是最好的方式,但在某些情况下,您可能需要使用字体样式。然而,该样式使用的是sp
,您可以通过以下方式将sp
转换为dp
:
fun TextView.getSizeInSp() = textSize / context.resources.displayMetrics.scaleDensity
fun TextView.convertToDpSize() = setTextSize(TypedValue.COMPLEX_UNIT_DIP, getSizeInSp())
sp
值而无需动态设置字体大小,也不需要硬编码字体大小。@Override
protected void attachBaseContext(Context newBase) {
final Configuration override = new Configuration(newBase.getResources().getConfiguration());
override.fontScale = 1.0f;
applyOverrideConfiguration(override);
super.attachBaseContext(newBase);
}
@Override
protected void attachBaseContext(Context newBase) {
Configuration old = newBase.getResources().getConfiguration();
final Configuration override = new Configuration(newBase.getResources().getConfiguration());
override.fontScale = 1.0f;
newBase = newBase.createConfigurationContext(override);
super.attachBaseContext(newBase);
}
override fun attachBaseContext(newBase: Context?) {
//Ignore font size changed in device settings and set the default
newBase?.resources?.configuration?.fontScale = 1.0f
super.attachBaseContext(newBase)
}
DisplayMetrics.scaledDensity
将不起作用,因为引入了fontScaleConverter
来处理字体缩放:
在活动中重写getResources()
方法如下所示:
override fun getResources(): Resources {
val resources = super.getResources()
resources.updateConfiguration(
Configuration(resources.configuration).apply {
fontScale = 1.0f
},
resources.displayMetrics
)
return resources
}