TextView.setTextSize behaves abnormally - How to set text size of textview dynamically for different screens
Solution 1:
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
Solution 2:
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 :)
Solution 3:
if Setting change font size,something cause show error,you can do as:
setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15.f);
Solution 4:
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>
Solution 5:
When we try to setText() programmitically problem with getTextSize(), returns value in px instead of sp/dp/dip and we know 1sp/dp=1.5px(screen size =240).
titleBar.setTextSize(TypedValue.COMPLEX_UNIT_SP, (getResources().getDimension(R.dimen.text_size)*1.5f));
is working perfectly for me or we can use displaymatrix to px:sp/dp ratio then replace that value with 1.5f
means-> titleBar.setTextSize(TypedValue.COMPLEX_UNIT_SP, (getResources().getDimension(R.dimen.text_size)*your_sp_and_px_ratio_in_int f));