简体   繁体   中英

Using Shared preferences to remember the font size that a user prefers in Android

I'm developing a mobile songbook android application. I have enabled text to be zoomed in or out. I want the application to be able to remember the specific font size that a user prefers when a user closes a specific song to another or even better even when a user closes the application and opens it again. Here is how i tried doing it:

public void saveFont(View view){
    SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putFloat("fontsize",factor.getInt());
    editor.apply();
}

public void rememberFont(View view){
    SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    double factor = sharedPref.getString("fontsize","");
    factor.setInt();
}

Here is the entire class:

public class SongbookActivity extends AppCompatActivity {
private TextView wordMeaning;
private TextToSpeech convertToSpeech;
ScaleGestureDetector scaleGestureDetector;
public double factor;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dictionary);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarSongActivity);
    TextView textViewTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
    setSupportActionBar(toolbar);


    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    int dictionaryId = bundle.getInt("SONG._ID");
    int id = dictionaryId + 1;


    wordMeaning = (TextView)findViewById(R.id.dictionary);


    String title = bundle.getString("SONG._TITLE");
    String description = bundle.getString("SONG._LYRICS");

    final android.support.v7.app.ActionBar ab = getSupportActionBar();
    ab.setHomeAsUpIndicator(R.drawable.left);
    ab.setTitle(null);
    ab.setDisplayHomeAsUpEnabled(true);


    textViewTitle.setText(title);

    textViewTitle.setSelected(true);
   // textViewTitle.setMovementMethod(new ScrollingMovementMethod());

    wordMeaning.setTextIsSelectable(true);

    registerForContextMenu(wordMeaning);
    wordMeaning.setMovementMethod(new ScrollingMovementMethod());
    wordMeaning.setText(description);
    scaleGestureDetector = new ScaleGestureDetector(this, new simpleOnScaleGestureListener());


    }


//copy text or select
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    //user has long pressed your TextView
    menu.add(0, v.getId(), 0, "Song copied to Clipboard");

    //cast the received View to TextView so that you can get its text
    TextView yourTextView = (TextView) v;

    //place your TextView's text in clipboard
    ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    clipboard.setText(yourTextView.getText());

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onTouchEvent(MotionEvent event) {


    if (event.getPointerCount() > 1) {
        scaleGestureDetector.onTouchEvent(event);
        return true;
    }
    return false;


}

public void saveFont(View view){
    SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putFloat("fontsize",factor.getInt());
    editor.apply();
}

public void rememberFont(View view){
    SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    double factor = sharedPref.getString("fontsize","");
    factor.setInt();
}

public class simpleOnScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        // TODO Auto-generated method stub
        float size = wordMeaning.getTextSize();
        Log.d("TextSizeStart", String.valueOf(size));

        float factor = detector.getScaleFactor();
        Log.d("Factor", String.valueOf(factor));

        float product = size*factor;
        Log.d("TextSize", String.valueOf(product));
        wordMeaning.setTextSize(TypedValue.COMPLEX_UNIT_PX, product);

        size = wordMeaning.getTextSize();
        Log.d("TextSizeEnd", String.valueOf(size));
        return true;
    }
}



@Override
public boolean onOptionsItemSelected(MenuItem item) {
    double factor = 1;
    float size = wordMeaning.getTextSize();
    saveFont(View view);
    rememberFont(View view);
    Log.d("TextSizeStart", String.valueOf(size));
    switch (item.getItemId()) {
        case R.id.small_layout:
            factor = 0.5;
            break;
        case R.id.medium_layout:
            factor = 0.9;
            break;
        case R.id.large_layout:
            factor = 1.3;
            break;
        case R.id.xlarge_layout:
            factor = 1.8;
            break;
    }



    Log.d("Factor", String.valueOf(factor));

    double product = size*factor;
    Log.d("TextSize", String.valueOf(product));
    wordMeaning.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float)product);

    size = wordMeaning.getTextSize();
    Log.d("TextSizeEnd", String.valueOf(size));
    return super.onOptionsItemSelected(item);



}

}

I'm getting errors when trying to call the method and on the method declaration. i'm a noob at this so please give me all the details you might think can help me, no matter how insignificant it can be.

here you will get all http://developer.android.com/training/basics/data-storage/shared-preferences.html actually you storing in float with int and trying to get in string so try below

public void saveFont(View view){
    SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt("fontsize",factor.getInt());
    editor.commit();
}

and from getting back

public void rememberFont(View view){
    SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    int  prevFont = sharedPref.getInt("fontsize",-1);

}

in -1 you can set your default font

Just a "light" how you can do this.

public void setVariable(float myFloat) {
    pref = _context.getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    editor = pref.edit();
    editor.putFloat("fontsize", myFloat);
    editor.commit();
}

public float getVariable() {
    pref = _context.getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    return pref.getFloat("fontsize", 5.5/*a default value*/);
}

_context can be an attribute.

EDIT1 : This class works FINE for me to any 'save' issues. Change this as your need

public class SharedPreferencesManager {

    // Shared Preferences
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private Context _context;

    // Shared pref mode
    private final int PRIVATE_MODE_SHARED_PREF = 0;

    // Shared preferences file name
    private final String PREF_NAME = "blabla";

    /*KEYS para o sharedpreferences*/
    private final String KEY_TO_USE = PREF_NAME + "setFont";


    public SharedPreferencesManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE_SHARED_PREF);
        editor = pref.edit();
    }

    public void setFont(float keySize) {
        editor.putFloat(KEY_TO_USE, keySize);
        editor.commit();
    }

        public boolean getFont() {
        return pref.getFloat(KEY_TO_USE, 15/*your default value is in here (in sp)*/);
    }
}

To use this, just create an object (passing the context[the activity]) and use the method GET in EVERY call/inflate of your EditText/TextView, and set the size like this

myTextView.setTextSize(mSharedPreferencesManagerObject.getVariable())

And to all of this make sense, on EVERY zoom changes, you need to call

mSharedPreference.setVariable(sizeHere)

It HAS to work. If not, the problem is in your "OnZoomChange" logic/semantic.

If you are having trouble with SharedPreferences, try using this . This greatly simplifies the whole process and uses SharedPreferences internally. All you have to do is copy the source file in your project and use it.

Here is an example:

In your activity's onCreate() method, initialize TinyDB.

TinyDB tinyDB = new TinyDB(this);

Then use it like this:

tinyDB.putString("fontSize", "12");

String fontSize = tinyDB.getString("fontSize");

As simple as that. There are many methods which are very useful in day to day development, just go through the source file once. Hope it helps.

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