Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set text size in .xml or programmatically

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?

like image 542
Suvitruf - Andrei Apanasik Avatar asked Oct 21 '13 14:10

Suvitruf - Andrei Apanasik


People also ask

How do I change font size in XML?

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 .

How do I set font size in programmatically?

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).

Can we change the text size programmatically?

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.


2 Answers

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 ) );
like image 62
323go Avatar answered Oct 20 '22 08:10

323go


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.

like image 36
Mark Avatar answered Oct 20 '22 10:10

Mark