I have variable at dimens.xml
<resources>
<dimen name="btn_text_size">12sp</dimen>
</resources>
And i can use it in layout file:
<TextView
android:textSize="@dimen/btn_text_size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/dialog_tags_complete"
/>
or programmatically
tagButton.setTextSize(c.getResources().getDimension(R.dimen.tag_text_size));
But this 2 methods give different results. I know that getDimension
are based on the current DisplayMetrics associated with the resources.
But what should i do to make this 2 ways looks the same?
Adding fonts to a TextView To set a font for the TextView , do one of the following: In the layout XML file, set the fontFamily attribute to the font file you want to access. Open the Properties window to set the font for the TextView .
To set Android Button font/text size, we can set android:textSize attribute for Button in layout XML file. To programmatically set or change Android Button font/text size, we can pass specified size to the method Button. setTextSize(specific_size).
A TextView in Android is a UI element to display text. It can be programmed in the layout file statically as well as in the main code dynamically. Thus, various attributes of a TextView such as the text, text color, text size, TextView background, and its size can be changed programmatically.
setTextSize( float )
expects a scaled pixel value. So, setTextSize( 12 )
would give you the desired result. However, getDimension()
and getDimensionPixelSize()
return the size in units of pixels, so you need to use the unit-typed variant of setTextSize()
as follows:
setTextSize( TypedValue.COMPLEX_UNIT_PX, getDimensionPixelSize( R.dimen.tag_text_size ) );
tagButton.setTextSize(c.getResources().getDimensionPixelSize(R.dimen.tag_text_size));
this will work just fine :) You should also remember that textView has a setTextSize(int unit,float size), which should be used while setting size from code but not from xml dimen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With