Android文本大小编程太大了

Ef *_* Ge 11 android textview

我有两个szenarios:

第一:

 textView.setTextSize(getResources().getDimension(R.dimen.defaultTextSize));
Run Code Online (Sandbox Code Playgroud)

xml中的第二个:

android:textSize="@dimen/defaultTextSize"
Run Code Online (Sandbox Code Playgroud)

在values/dimen.xml中,我已经使用20sp声明了defaultTextSize

在我的第一种情况下,文本比我的第二种情况要大得多(并且在某些屏幕上不同).为什么?我做错了吗?

Roh*_*5k2 15

setTextSize() 将单位作为像素

用这个

public float pixelsToSp(float px) 
{
    float scaledDensity = _context.getResources().getDisplayMetrics().scaledDensity;
    return px/scaledDensity;
}

textView.setTextSize(pixelsToSp(getResources().getDimension(R.dimen.defaultTextSize)));
Run Code Online (Sandbox Code Playgroud)

要么

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.defaultTextSize))
Run Code Online (Sandbox Code Playgroud)

  • 绝对不知道为什么,但第二个建议不适用于我的GalaxyS4.Oi Vey Android ......但解决方案1工作,谢谢. (2认同)
  • @Kufuma它不起作用,因为它是错误的:应该是COMPLEX_UNIT_PX而不是COMPLEX_UNIT_SP。另请参阅此页中Blackbelt的答案。 (2认同)

Bla*_*elt 9

实施 setTextSize(float size)

public void setTextSize(float size) {
    setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}
Run Code Online (Sandbox Code Playgroud)

在您的情况下,正在发生的是您正在缩放您提供的值setTextSize,因为getDimension返回维度乘以度量.试试吧

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.defaultTextSize));
Run Code Online (Sandbox Code Playgroud)