Search code examples
androidsharedpreferencestextviewtext-size

Orientation change increases TextView's text size


I want to save my current text size by SharedPreferences, and set it back when screen orientation is changed.

I use this code, but when I change the screen orientation it makes the textSize bigger...

package com.example.zz;

import android.app.ActionBar;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView text;
    float size;
    ActionBar actionBar;
    private final String TEXT_SIZE = "textsize";
    final String MyPref = "preference";
    SharedPreferences settings;
    Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.textView1);

        settings = this.getSharedPreferences(MyPref, 0);
        text.setTextSize(settings.getFloat(TEXT_SIZE, 0));
        editor = settings.edit();
    }

    public void sizeUp(MenuItem item) {
        size = text.getTextSize();
        text.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float) (size + 5));

    }

    public void sizeDown(MenuItem item) {
        size = text.getTextSize();
        text.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float) (size - 5));

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.actionbar, menu);
        return true;
    }

    @Override
    protected void onStop() {
        super.onStop();

        SharedPreferences.Editor editor = settings.edit();
        editor.putFloat(TEXT_SIZE, text.getTextSize());

        editor.commit();
    }

}

Thanks.


Solution

  • Method getTextSize() returns text size in pixels, but setTextSize() treats the size in sp units. That's why your text looks bigger. You should scale the size before using in setTextSize(). You can do like this:

    SharedPreferences.Editor editor = settings.edit();
    editor.putFloat(TEXT_SIZE, text.getTextSize()/getResources().getDisplayMetrics().scaledDensity); // put text size in sp
    editor.commit();