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

Viewed 103566

Calling TextView.setTextSize() is working abnormally. Right after the call to setTextSize if we get a getTextSize its returning a much higher value that what we set it to earlier.

Here's what we're doing:

zoomControl.setOnZoomInClickListener(new OnClickListener() {
    public void onClick(View view) {
        float size = mViewShabad.getTextSize() + 1;
        textView.setTextSize(size);
    }
});

Has anyone seen this before?

8 Answers

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>

Kotlin Solution

To set using a resource, just use this:

textView.setTextSize(COMPLEX_UNIT_PX, textView.resources.getDimension(R.dimen.my_text_size))

To do the same with a resource value, add this extension property to much more easily set your text size

textView.textSizeRes = R.dimen.my_text_size

var TextView.textSizeRes
    get() = textSize.toInt()
    set(@DimenRes textSizeRes) {
        setTextSize(COMPLEX_UNIT_PX, resources.getDimension(textSizeRes))
    }
Related