按钮中的共享首选项

时间:2020-01-05 15:53:00

标签: android button sharedpreferences

我正在尝试将背景更改和按钮状态保存在sharedpreferences中,在这种情况下,这就像一个新的解锁级别,用户需要一个分数才能解锁该级别,但是当离开应用程序时,他恢复了正常状态,我该怎么做才能保存此更改? 请帮助我,我已经在几个地方搜索了答案,但是我没有成功,如果您能帮助我,我将非常感激!

enter image description here

ImageView imagem;
Button button,buttonScore;
TextView mScore;
private boolean newLevel = false;
private int score = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imagem = findViewById(R.id.nivel);
    button = findViewById(R.id.botao);
    buttonScore = findViewById(R.id.bonusescore);
    mScore = findViewById(R.id.score);

    final SharedPreferences sharedPreferences = getSharedPreferences("USER",MODE_PRIVATE);

    mScore.setText("" + score);

    buttonScore.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            score += 20;
            mScore.setText("" + score);
        }
    });

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(!newLevel){
                if (score > 19){
                    score += -20;
                    mScore.setText("" + score);
                    imagem.setBackgroundColor(getResources().getColor(R.color.azul));
                    button.setText("UNLOCKED");
                    button.setEnabled(false);
                    newLevel=true;
                }

            }else {
                imagem.setBackgroundColor(getResources().getColor(R.color.vermelho));
                button.setText("LOCKED");
                button.setEnabled(true);
                newLevel=false;

            }
        }
    });

}

}

2 个答案:

答案 0 :(得分:0)

因此,您需要保存得分或btn状态。

SharedPreferences提供了用于读取和保存此数据的接口。

为了读取值:

sharedPreferences.getString(key1, default_value);
sharedPreferences.getBoolean(key2, default_value);

为了节省价值:

sharedPreferences.edit().putBoolean(key1, value).apply();
sharedPreferences.edit().putString(key2, value).apply();

官方文档:https://developer.android.com/training/data-storage/shared-preferences

答案 1 :(得分:0)

使用以下代码:

 final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("USER",MODE_PRIVATE);
    SharedPreferences.Editor editor_user = sharedPreferences.edit();

    editor_user.putBoolean("button_clicked", button.isSelected());
    editor_user.putBoolean("buttonScore_clicked", buttonScore.isSelected());
    editor_user.apply();

    Boolean boolean = editor_user.getBoolean("button_clicked",false);

    if(boolean == true)
    {
     imagem.setBackgroundColor(getResources().getColor(R.color.azul));
    }
    else
    {
    imagem.setBackgroundColor(getResources().getColor(R.color.vermelho));
    }