How to set text size of textview dynamically for different screens
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:
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.textsize));
Note you can also use
getResources().getDimensionPixelSize(R.dimen.textSize);
instead of getDimension()
and it will round and convert to an non fractional value.
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>
EDIT: 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.