Textview.Settextsize Behaves Abnormally - How to Set Text Size of Textview Dynamically for Different Screens

How to set text size of textview dynamically for different screens

You should use the resource folders such as

values-ldpi
values-mdpi
values-hdpi

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

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

textView.setTextSize(getResources().getDimension(R.dimen.textsize));

Sample dimensions.xml

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

TextView.setTextSize behaves abnormally - How to set text size of textview dynamically for different screens

The difference here is that in the setTextSize(int size) method, the unit type by default is "sp" or "scaled pixels". This value will be a different pixel dimension for each screen density (ldpi, mdpi, hdpi).

getTextSize(), on the other hand, returns the actual pixel dimensions of the text.

You can use setTextSize(int unit, float size) to specify a unit type. The constant values for this can be found in the TypedValue class, but some of them are:

TypedValue.COMPLEX_UNIT_PX   //Pixels

TypedValue.COMPLEX_UNIT_SP //Scaled Pixels

TypedValue.COMPLEX_UNIT_DIP //Device Independent Pixels

Android TextView setTextSize incorrectly increases text size

Heh, mixed units problem. Seems a little counterintuitive, but it's an easy fix. The default method setTextSize(float) assumes you're inputting sp units (scaled pixels), while the getTextSize() method returns an exact pixel size.

You can fix this by using the alternate setTextSize(TypedValue, float), like so:

this.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);

This will make sure you're working with the same units.

Strange behaviour when reuse the text size of TextView

The difference here is that in the setTextSize(int size) method, the
unit type by default is "sp" or "scaled pixels". This value will be a
different pixel dimension for each screen density (ldpi, mdpi, hdpi).

getTextSize(), on the other hand, returns the actual pixel dimensions
of the text.

It also explains your issue. The full thread link is here

If you want to convert them then:

public static float pixel2Sp(Context context, float px) {
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
return px/scaledDensity;
}

textView.setTextSize(pixel2Sp(context, textView.getTextSize());


Related Topics



Leave a reply



Submit