使用SharedPreference保存用户详细信息

时间:2017-01-01 21:39:02

标签: android sharedpreferences

我知道保存值的最佳方法是使用SharedPreferences,例如

SharedPreferences Savesettings = getSharedPreferences("settingFile", MODE_PRIVATE);
        SharedPreferences.Editor example = Savesettings.edit();
        example.putString("Name", name)
                .putInt("Age", age)
                .putInt("Score", score)
        example.apply();

但是,如果我希望我的程序在用户关闭并打开程序后记住按钮被禁用或启用,该怎么办?我已经尝试了RegisterOnChangePreferanceListener但是我没有运气,例如。

SharedPreferences Preferences= PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.OnSharedPreferenceChangeListener Example =
                new SharedPreferences.OnSharedPreferenceChangeListener() {
                    public void onSharedPreferenceChanged(SharedPreferences preferance, String key) {

                        Name = name;//only an example not the main focus
                        Age = age;
                        Score = score;
                        enableBTN = false; //disables button
                        Name.setEnabled(false); //disables the edit text from further editing
}
                };
        Preferences.registerOnSharedPreferenceChangeListener(Example);

有没有办法做到这一点,这两种方法似乎都不适合我。

1 个答案:

答案 0 :(得分:1)

您需要在按钮的OnClickListener内保存。这样,每次单击按钮时,都可以保证按钮的状态被保存。 button是对Button视图对象

的引用
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle bundle) {
        Button button = (Button)findViewById("this_button_view_id");
        EditText editText = (EditText)findViewById("this_edit_text_id");
        SharedPreferences Savesettings = getSharedPreferences("settingFile", MODE_PRIVATE);

        // If the Savesettings shared preferences above contains the "isButtonDisabled" key
        // It means the user clicked and disabled the button before
        // So we use that state instead
        // If it does does not contain that key
        // We set it to true so that the button is not disabled
        // Same for the edit text
        button.setEnabled(Savesettings.contains("isButtonDisabled") ? Savesettings.getBoolean("isButtonDisabled") : true);
        editText.setEnabled(Savesettings.contains("isEditTextDisabled") ? Savesettings.getBoolean("isEditTextDisabled") : true);

        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // disable the edit text
                editText.setEnabled(false);

                // disable the button
                button.setEnabled(false);

                SharedPreferences.Editor example = Savesettings.edit();

                // Save the button state to the shared preferences retrieved above
                example.putBoolean("isButtonDisabled", true);

                // Save the edit text state to the shared preferences retrieved above
                example.putBoolean("isEditTextDisabled", true);
                example.apply();

            }
        });
    }
}