0

i add a menu to change color of text and i want to keep the color even after exit activity or the app is closed

public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){

        case R.id.red :
            txt.setTextColor(red);
            break;

        case R.id.green :
            txt.setTextColor(Color.parseColor("#03A136"));
            return true;

        case R.id.blue :
            txt.setTextColor(Color.parseColor("#222CA1"));
            return true;

        case R.id.black :
            txt.setTextColor(Color.BLACK);
            return true;

        case R.id.brown :
            txt.setTextColor(Color.parseColor("#CC805C"));
            return true;
    }
    return super.onOptionsItemSelected(item);
}
  • Use SharedPreference. [See this](https://www.tutorialspoint.com/android/android_shared_preferences.htm) – Sniffer Apr 15 '21 at 04:56

1 Answers1

1

you can use SharedPreferences to store your color throughtout the application life

public class SaveColor {

private Context context;
private SharedPreferences sharedPreferences;
private int color;


public void setColor(int color){
sharedPreferences.edit().putInt("color",color).commit();
}

public boolean getColor(){
color = sharedPreferences.getInt("color");
}

public SaveColor(Context context){
    this.context = context;
    sharedPreferences = 
    context.getSharedPreferences("SaveColor",Context.MODE_PRIVATE);
}

}




// And use it in your activity like this
SaveColor saveColor = new SaveColor(this);

public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){

    case R.id.red :
        txt.setTextColor(red);
        saveColor.setColor(your color id);
        break;

    case R.id.green :
        txt.setTextColor(Color.parseColor("#03A136"));
        saveColor.setColor(your color id);
        return true;

    case R.id.blue :
        txt.setTextColor(Color.parseColor("#222CA1"));
        saveColor.setColor(your color id);
        return true;

    case R.id.black :
        txt.setTextColor(Color.BLACK);
        saveColor.setColor(your color id);
        return true;

    case R.id.brown :
        txt.setTextColor(Color.parseColor("#CC805C"));
        return true;
}
return super.onOptionsItemSelected(item);
}
D_K
  • 152
  • 2
  • 9