Inconsistency when setting TextView font size in code and in resources

The official documentation is not responding to this, or I cannot figure it out.

Element (never pay attention to AlertDialog , this happens on any TextView):

 TextView tv = (TextView) dialog.findViewById(android.R.id.message); 

Inconsistency. Case A:

 tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); // or tv.setTextSize(14); does the same 

Case B:

 tv.setTextSize(getResources().getDimension(R.dimen.text_size_small)); // TypedValue makes no difference either. 

where values/dimens.xml has:

 <dimen name="text_size_small">14sp</dimen> 

Result: the font size does not match, and it appears much larger when extracted from the resource. I probably missed something, so my mistake and most importantly: why?

- UPDATE OF THE FIRST ANSWER -

A fixed number was just an example, since no one could rigidly fix the font size in the code. So let me rephrase the question:

Why, if I get the resource from the code, the text size is larger than when I get the resource from the XML layout? . In addition, the question remains the same: how to get the 14sp unit in the code and maintain it in accordance with the 14sp unit that is installed in the XML layout? I did not accept the answer because it does not tell me how to use sp units from a resource in the code for text size.

In this layout, the font size is different even if the size is the same:

 <TextView android:id="@+id/my_text" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/TextBody" /> 

styles.xml:

 <style name="TextBody"> <item name="android:textSize">@dimen/text_size_small</item> <item name="android:lineSpacingMultiplier">1.1</item> <item name="android:textColor">@color/body_text_1</item> <item name="android:textIsSelectable">true</item> <item name="android:linksClickable">true</item> </style> 

See text_size_small? Why, in this case, is the font size smaller than in the code using the same dimen resource?

+59
android dimension dialog text-size
Jul 22 '11 at 0:13
source share
3 answers

You should use setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); , because the documentation for the getDimension method indicates that it returns Resource dimension value multiplied by the appropriate metric. , which, as I understand it, is the pre-calculated absolute value of px.

That is, use:

 tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_size_small)); 
+100
Aug 13 '11 at 18:03
source share

Somehow it seems appropriate:

XML:

 <?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="typo14">9sp</dimen> </resources> 

Java:

 setTextSize(TypedValue.COMPLEX_UNIT_SP, 9); setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.typo14)); 
+22
Feb 20 2018-12-12T00:
source share

This is a question sp px dpi

 tv.setTextSize(14) = 14 pixels 
+2
Jul 22 2018-11-11T00
source share



All Articles