简体   繁体   中英

How to change font size of an app in android studio using seekbar

I'm trying to change the font of the overall app by using a seekbar in the settings activity that I've created. Below is what I have gotten from online so far, but it changes only the small amount of text with the ID "changeFont":

// Fonts Scale Slider
fontScaleSlider = findViewById(R.id.fontScaleSlider);
view = findViewById(R.id.changeFont);

prefs = getPreferences(MODE_PRIVATE);

float fs = prefs.getFloat("fontsize", 10);
fontScaleSlider.setProgress((int)fs);
view.setTextSize(fontScaleSlider.getProgress());


fontScaleSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

    @Override
    public void onStopTrackingTouch(SeekBar fontScaleSlider){
        prefs = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor ed = prefs.edit();
        ed.putFloat("fontsize", view.getTextSize());
        ed.commit();
    }
    @Override
    public void onStartTrackingTouch(SeekBar fontScaleSlider) {

    }
    @Override
    public void onProgressChanged(SeekBar fontScaleSlider, int progress,
                                  boolean fromUser){
        view.setTextSize(progress);
        // Set text size of the whole app here
    }

And the XML file:

<SeekBar
            android:id="@+id/fontScaleSlider"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_marginStart="13dp"
            android:layout_marginEnd="13dp"
            android:layout_marginBottom="82dp"
            android:max="30"
            app:layout_constraintBottom_toTopOf="@+id/logInButton"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/fontSliderLabel" />

In the implemented method onProgressChanged you can save the seek bar value to the shared preferences.

@Override
public void onProgressChanged(SeekBar fontScaleSlider, int progress,boolean fromUser){
    SharedPreferences.Editor ed = prefs.edit();
    ed.putInt("fontSize", progress);
    ed.apply();
}

And then use the saved value to set the text size of each text when the activity starts

int textSize = prefs.getInt("fontSize", defaultValue); // put your default value here like 16
textView.setTextSize(textSize);
//similarly set the textsize for other views

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM