ui更改的onclicklistener在第一次点击时不会更新

时间:2019-07-07 12:46:42

标签: android sharedpreferences buttonclick

我遇到一个问题,我试图在单击事件时更改Button的前景。前景仅在第一次单击后更改。

public void muteSoundClick(View view){
        playSound = preferences.getBoolean("playSound", true);

        if (playSound) {
            view.setForeground(getDrawable(R.drawable.foreground_padding_unmute));
            editor.putBoolean("playSound", false);
            editor.apply();
        }
        else {
            view.setForeground(getDrawable(R.drawable.foreground_padding_mute));
            editor.putBoolean("playSound", true);
            editor.apply();
        }
    }

我从android SharedPrefernces中检索了一个变量,该变量用于确定要使用的前景。

2 个答案:

答案 0 :(得分:1)

首先,您需要在活动开始时检查播放声音,以便按钮本身会得到您第一次保存的内容,因此您需要这样的东西:

    playSound = preferences.getBoolean("playSound", true);

    if(playSound)
        button.setForeground(getDrawable(R.drawable.foreground_padding_mute));
    else

     button.setForeground(getDrawable(R.drawable.foreground_padding_unmute));

然后,您可以使用在问题中发布的方法处理点击次数

这是一个示例示例活动,总结起来:

public class SimpleActivity extends AppCompatActivity {

SharedPreferences preferences;
SharedPreferences.Editor editor;
boolean playSound;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_simple);

    preferences = PreferenceManager.getDefaultSharedPreferences(this);
    editor= PreferenceManager.getDefaultSharedPreferences(this).edit();
    Button button = findViewById(YourButtonID);
        playSound = preferences.getBoolean("playSound", true);

        if(playSound)
            button.setForeground(getDrawable(R.drawable.foreground_padding_mute));
        else
            button.setForeground(getDrawable(R.drawable.foreground_padding_unmute));

}


public void muteSoundClick(View view){
    playSound = preferences.getBoolean("playSound", true);

    if (playSound) {
        view.setForeground(getDrawable(R.drawable.foreground_padding_unmute));
        editor.putBoolean("playSound", false);
        editor.apply();
    }
    else {
        view.setForeground(getDrawable(R.drawable.foreground_padding_mute));
        editor.putBoolean("playSound", true);
        editor.apply();
    }
}

}

答案 1 :(得分:0)

似乎您并不是在真正编辑首选项。这样。

SharedPreferences.Editor editor;

public void muteSoundClick(View view){
    playSound = preferences.getBoolean("playSound", true);

    if (playSound) {
        editor = sharedPreferences.edit();
        view.setForeground(getDrawable(R.drawable.foreground_padding_unmute));
        editor.putBoolean("playSound", false);
        editor.commit();
    }
    else {
        view.setForeground(getDrawable(R.drawable.foreground_padding_mute));
        editor.putBoolean("playSound", true);
        editor.apply();
    }
}