为这个答案添加了一些额外的味道,也带来了一些混乱。您应该能够将此测试放入项目中的任何@RunWith(AndroidJUnit4.class)
测试中(还需要将dimens添加到您的dimens.xml中)。
注意:所有这些测试均通过
@Test public void testScaledFontSizes() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
final Context context = InstrumentationRegistry.getTargetContext();
Configuration configuration = context.getResources().getConfiguration();
configuration.fontScale = 2.0f;
configuration.densityDpi = 160; // mdpi, 1:1
context.getResources().updateConfiguration(configuration, null);
float scaledTextSize = context.getResources().getDimensionPixelSize(R.dimen.sp_15);
assertEquals(30.0f, scaledTextSize);
// Create a new TextView with the explicitly set configuration
TextView textView = new TextView(context);
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, scaledTextSize);
// 30, because font size is scaled
assertEquals(30.0f, textView.getTextSize());
// This is what we *don't* want, it's scaled *twice*!
textView.setTextSize(scaledTextSize);
assertEquals(60.0f, textView.getTextSize());
// DP instead of SP tests
float fifteenDp = context.getResources().getDimensionPixelSize(R.dimen.dp_15);
assertEquals(15.0f, fifteenDp);
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, fifteenDp);
// Still 15, because it's DP, not SP
assertEquals(15.0f, fifteenDp);
textView.setTextSize(fifteenDp);
// 30, because setTextSize DOES font scaling
assertEquals(30.0f, textView.getTextSize());
}
}
我发现最大的收获是TextView.setTextSize(float)
应用了字体缩放,因此,如果传入已经被标记为SP而不是DP的dimen thats,它将收到两次字体缩放。