Android应用程序中TextView的字体大小会随着本机设置更改字体大小而变化
我想在我的应用程序中指定自己的文本大小,但是我在执行此操作时遇到问题。
当我在设备设置中更改字体大小时,我的应用程序TextView的字体大小也会更改。
9个解决方案
184 votes
实际上,设置字体大小仅影响dp中的大小。所以您需要做的 - 在dp而不是sp中定义sp,然后设置不会更改您的应用中的文本大小。
这是文档的链接:尺寸
但请注意,预期的行为是所有应用程序中的字体都尊重用户的首选项。 用户可能想要调整字体大小的原因有很多,其中一些甚至可能是医学视觉障碍用户。 使用dp代替sp文本可能会导致不情愿地歧视您的某些应用程序的用户。
即:
android:textSize="32dp"
sandrstar answered 2019-05-19T17:08:24Z
126 votes
最简单的方法就是使用如下内容:
android:textSize="32sp"
如果您想了解有关textSize属性的更多信息,可以查看Android开发人员文档。
Evan Long answered 2019-05-19T17:08:58Z
43 votes
使用像您一样使用android:textSize类型的资源(DOCS)。
在android:textSize文件中,声明维度变量:
25dp
150dp
30dp
16sp
然后你可以像这样使用这些值:
android:layout_height="@dimen/textview_height"
android:layout_width="@dimen/textview_width"
android:textSize="@dimen/font_size"/>
您可以为不同类型的屏幕声明不同的android:textSize文件。这样做可以保证您的应用在不同设备上的外观。
如果未指定android:textSize,则系统将使用默认值。
ashakirov answered 2019-05-19T17:09:59Z
23 votes
另请注意,如果textSize在代码中设置,则调用textView.setTextSize(X)将数字(X)解释为SP。 使用setTextSize(TypedValue.COMPLEX_UNIT_DIP, X)在dp中设置值。
Arpit answered 2019-05-19T17:10:26Z
12 votes
在dimen.xml文件中定义时,必须通过代码再次指定DIP或SP并不是一件好事。
我认为最好的选择是在使用dimen.xml值时使用PX:
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.txt_size));
这样,您可以在dimen.xml文件中根据需要从DP切换到SP,而无需更改任何代码。
mba answered 2019-05-19T17:11:08Z
4 votes
防止整个应用程序受系统字体大小影响的简单方法是使用基本活动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());
}
Usama Saeed US answered 2019-05-19T17:11:35Z
1 votes
在textSize中使用DP中的字体大小而不是SP解决了这个问题。
bpr10 answered 2019-05-19T17:12:02Z
1 votes
这可能有所帮助。 在自定义应用程序或BaseActivity中添加代码
/**
* 重写 getResource 方法,防止系统字体影响
*
* @return
*/
@Override
public Resources getResources() {
Resources resources = super.getResources();
if (resources != null && resources.getConfiguration().fontScale != 1) {
Configuration configuration = resources.getConfiguration();
configuration.fontScale = 1;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
}
return resources;
}
但是,Resource#updateConfiguration在API级别25中被删除,这意味着将来某天将不支持它。
Arno_J answered 2019-05-19T17:12:38Z
1 votes
您必须使用XML编写TextView标记:
android:textSize="32dp"
neha answered 2019-05-19T17:13:06Z