我想在我的应用程序中指定我自己的文本大小,但我这样做有一个问题。
当我在设备设置中改变字体大小时,我的应用程序TextView的字体大小也会改变。
我想在我的应用程序中指定我自己的文本大小,但我这样做有一个问题。
当我在设备设置中改变字体大小时,我的应用程序TextView的字体大小也会改变。
当前回答
还要注意,如果在代码中设置了textSize,调用textView.setTextSize(X)将数字(X)解释为SP。COMPLEX_UNIT_DIP, X)在dp中设置值。
其他回答
在android 8中,这个解决方案适合我
在基本活动中添加此代码
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
final Configuration override = new Configuration(newBase.getResources().getConfiguration());
override.fontScale = 1.0f;
applyOverrideConfiguration(override);
}
源 https://stackoverflow.com/a/57225687/7985871
最简单的方法就是使用如下代码:
android:textSize="32sp"
如果你想了解更多关于textSize属性的信息,你可以查看Android开发者文档。
对于kotlin,这对我来说是有效的
priceTextView.textSize = 12f
防止整个应用程序受到系统字体大小影响的简单方法是使用一个基本活动updateConfiguration。
//in base activity add this code.
public void adjustFontScale( Configuration configuration) {
configuration.fontScale = (float) 1.0;
DisplayMetrics metrics = getResources().getDisplayMetrics();
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
metrics.scaledDensity = configuration.fontScale * metrics.density;
getBaseContext().getResources().updateConfiguration(configuration, metrics);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adjustFontScale( getResources().getConfiguration());
}
在Activity中重写getResources()。
设置TextView的大小在sp通常像android:textSize="32sp"
override fun getResources(): Resources {
return super.getResources().apply {
configuration.fontScale = 1F
updateConfiguration(configuration, displayMetrics)
}
}