Search code examples
javaandroidandroid-spinnertext-size

Change TextSize with a spinner


I managed to change the color of a certain text with a spinner. But now I wanted to change the size of the same text with another spinner. I put the color cases inside a switch function to change the color.

like that

switch (i) {
                case 0:
                    description.setText(des[i]);
                    preferences.edit().putInt(SELECTED_COLOR, Color.WHITE).apply();
                    break;
                case 1:
                    description.setText(des[i]);
                    preferences.edit().putInt(SELECTED_COLOR, Color.BLUE).apply();
                    break;

I wrote all down but I dont know how to call the TextSize inside the case. I thought it would work like that:

 switch (d) {
                case 0:
                    description2.setText(des2[d]);
                    preferences2.edit().putInt(SELECTED_SIZE, ????); <==
            }
        }

But I cant use TextSize or something like that. To change the color I used Color.BLUE/RED/GREEN/... but now I want to change the TextSize... It is as always kind of difficult to explain my problem^^ sry for that.


Solution

  • If you want to use shared preferences and a switch statement like you do for your colors, you can do something similar to the following:

    In your switch statement, similar to how you are handling color, add the text size associated with the selected spinner index to your shared preferences:

    switch(i) {
        case 0:
            preferences.edit().putInt(SELECTED_SIZE, 16).apply();
            break;
        case 1:
            preferences.edit().putInt(SELECTED_SIZE, 18).apply();
            break;
        // other cases go here...
    }
    

    Then, in the activity that includes the TextView whose text size you want to change (in this example, named textViewToChange), retrieve the saved value, and use it to set the text size:

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    int selectedTextSize = preferences.getInt(SELECTED_SIZE, 0);
    textViewToChange.setTextSize(TypedValue.COMPLEX_UNIT_SP, selectedTextSize);