Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Which method is used to change the text size of the TextView?

To use preset sizes to set up the autosizing of TextView programmatically, call the setAutoSizeTextTypeUniformWithPresetSizes(int[] presetSizes, int unit) method. Provide an array of sizes and any TypedValue dimension unit for the size.

Which attribute increases or decreases the font size of TextView select one?

app:autoSizeMinTextSize=”10sp” using this attribute the TextView will be resized up to the size of 10sp and app:autoSizeStepGranularity=”2sp” using this attribute we are uniformly reducing the size of the TextView as 2sp when it goes out of the screen.

How do I limit text in TextView?

you can extend the TextView class and overwrite the setText() function. In this function you check for text length or word cound. Better than counting the text length or the word cound a better way would be to use the "maxLines" attribute along with "ellipsize" attribute to attain the desired effect.


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

this problem happend because the getTextSize() method return the size in pixels depend on screen density ! to get the Actual TextSize use this :

DisplayMetrics metrics;
metrics = getApplicationContext().getResources().getDisplayMetrics();
float Textsize =myTextView.getTextSize()/metrics.density;
myTextView.setTextSize(Textsize+1);

i hope it solve it :)


if Setting change font size,something cause show error,you can do as:

setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15.f);

After long time struck this and finally solved like this

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
          getResources().getDimension(R.dimen.textsize));

create dimen folder like this res/values/dimensions.xml

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

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

 </resources>