Let the user change font size

1.7k views Asked by At

in my dimens.xml I've:

<dimen name="text_small">16sp</dimen>
<dimen name="text_normal">18sp</dimen>
<dimen name="text_medium">20sp</dimen>
<dimen name="text_big">22sp</dimen>

now I would like to let the user select the font size in a settings fragment. Let's say for example:

  1. Small -2sp
  2. Normal +0sp
  3. Medium +2sp
  4. Big +4sp

So for example if the user select "Big" I would like that font size will be:

<dimen name="text_small">20sp</dimen>
<dimen name="text_normal">22sp</dimen>
<dimen name="text_medium">24sp</dimen>
<dimen name="text_big">26sp</dimen>

Is there a way to do something like:

Application Start:

if (sizeUser.equals("Big")) {
    text_small=24sp
.....
}

and so on?

2

There are 2 answers

1
mattfred On

You don't need to use dimens.xml. Instead, use setTextSize

TextView tv = findViewById(R.id.textView);

if ("Big".equals(sizeUser) {
    tv.setTextSize(26);
}
4
Chris Stillwell On

Rather than have to call setTextSize for every TextView in every Activity I'd create a custom class that extends TextView and then contains the logic for setting the text size in its setTextSize.

public class MyTextView extends TextView {

    public MyTextView(Context context) {
        super(context);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setTextSize (int unit, float size){
        switch(USER_SET_SIZE){
            case SMALL:
                setTextSize(TypedValue.COMPLEX_UNIT_SP, -2);
                break;
            case MEDIUM:
                setTextSize(TypedValue.COMPLEX_UNIT_SP, 2);
                break;
            case LARGE:
                setTextSize(TypedValue.COMPLEX_UNIT_SP, 4);
                break;
            case NORMAL:
            default:
                setTextSize(TypedValue.COMPLEX_UNIT_SP, 0);
                break;
        }
    }
}

Or if you are using multiple views and want to control the text size of each I'd recommend using themes then change your theme based on your font size. Simply call setTheme() in your Activity's onCreate() first.

Your theme files should look like this

<style name="NormalSizeTheme" parent="@style/MyTheme">
    <item name="android:textSize">0sp</item>
</style>