Home » Android » android – How to set text size of textview dynamically for different screens

android – How to set text size of textview dynamically for different screens

Posted by: admin March 11, 2020 Leave a comment


I am creating a textview and adding to the layout dynamically. I am using textView.setTextSize(18) method to set the text size.I tested it on samsung tablet and found that the font size is too small for this screen then I changed the textsize to 25 but it is too big for an emulator(480*800). My problem is to set text size dynamically so that it fits for all the screens.

How to&Answers:

You should use the resource folders such as


And write the text size in ‘dimensions.xml’ file for each range.

And in the java code you can set the text size with


Sample dimensions.xml

<?xml version="1.0" encoding="utf-8"?>
    <dimen name="textsize">15sp</dimen>


And As I Search on StackOverflow now I found This Question is Duplicate of : This and This

You need to use another function setTextSize(unit, size) with unit SP like this,

tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f);

Please read more for TypedValue constants.


There is probably no need to use the ldpi , mdpi or hdpi qualifiers in this case.

When you define a dimension in a resource file you include the measurement unit. If you use sp units they are scaled according to the screen density so text at 15sp should appear roughly the same size on screens of differing density.
(The real screen density of the device isn’t going to exactly match as Android generalises screen density into 120, 160, 240, 320, 480 and 640 dpi groups.)

When calling getResources().getDimension(R.dimen.textsize) it will return the size in pixels. If using sp it will scaled by the screen density,

Calling setText(float) sets the size in sp units. This is where the issue is,
i.e you have pixels measurements on one hand and sp unit on the other to fix do this:


Note you can also use


instead of getDimension() and it will round and convert to an non fractional value.


After long time stuck this issue, finally solved like this


create folder like this res/values/dimens.xml

<?xml version="1.0" encoding="utf-8"?>

  <dimen name="textsize">8sp</dimen>



In Style.xml pre-define the style:

<style name="largeText">
    <item name="android:textAppearance">@android:style/TextAppearance.Large.Inverse</item>
    <item name="android:textStyle">bold</item>

in code:

text.setTextAppearance(context, R.style.largeText);


I think You should use the textView.setTextSize(float size) method to set the size of text. textView.setText(arg) used to set the text in the Text View.


float currentSize = textEdit.getTextSize(); // default size
float newSize = currentSize * 2.0F; // new size is twice bigger than default one