Search code examples
androidtextviewtext-size

Strange behaviour when reuse the text size of TextView


I want to scale my textview font size, however, I could not understand its behavior from very simple code so I cannot control the font size.

 TextView textView = (TextView)findViewById(R.id.textview2);
 textView.setTextSize(textView.getTextSize());

The font size was supposed not to change, but the textView changed its font size while I used the same value from getTextSize() method. Can anyone explain?


Solution

  • 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());