Adding some extra flavor for this answer, as also ran into a bit of confusion. You should be able to drop this test into any @RunWith(AndroidJUnit4.class)
test you have in your project (you'll also need to add the dimens to your dimens.xml).
Note: All these tests pass
@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());
}
}
The big takeaway I found is that TextView.setTextSize(float)
applies the font scaling, so if you pass in a dimen thats already labelled as SP instead of DP, then it will receive the font scaling twice.