我想使用从一个活动到另一个活动的共享首选项的值,例如,如果我的pin_activity的引脚设置为on,则应禁用来自另一个活动的模式,并显示" PinService为ON的Toast ,你不能开启PatternService"反之亦然。我没有得到如何使用共享偏好值。请帮我解决这个问题
这是我的两个活动的代码。
pin_activity.java
s2 = (Switch) findViewById(R.id.switch2);
spref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
s2.setChecked(spref.getBoolean("SwitchButton", false));
s2.setOnClickListener(new ToggleButton.OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("SwitchButton", s2.isChecked());
// editor.putString("switch_state", "value");
//switch_state=editor.putBoolean("SwitchButton", s2.isChecked());
editor.commit();
// Toast.makeText(getApplicationContext(), "Switch is ON", Toast.LENGTH_SHORT).show();
}
});
Pattern_activity.java
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
s1.setChecked(sharedPreferences.getBoolean("toggleButton", false));
switch1= sharedPreferences.getBoolean("editor",s1.isChecked() );
if (switch1== true)
{
s1.setEnabled(false);
Toast.makeText(getApplicationContext(), "PinService is ON, You can't Make PatternService ON", Toast.LENGTH_SHORT).show();
}
else
{
s1.setEnabled(true);
}
s1.setOnClickListener(new ToggleButton.OnClickListener() {
public void onClick(View v) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
//switch1= sharedPreferences.getString("switch_state", null);
editor.commit();
// Toast.makeText(getApplicationContext(), "Switch is ON", Toast.LENGTH_SHORT).show();
}
});
答案 0 :(得分:1)
您需要使用相同的密钥进行设置。
在您的示例中,您使用“SwitchButton”来读取/写入pin_activity中的开关状态,使用“editor”来读取(假设)相同的值。哪个不行。
因此,将关键字符串提取为常量,如public static String PIN_STATE = "PIN_STATE";
。
in pin_activity:
s2 = (Switch) findViewById(R.id.switch2);
spref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
s2.setChecked(spref.getBoolean(PIN_STATE, false));
s2.setOnClickListener(new ToggleButton.OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean(PIN_STATE, s2.isChecked());
// editor.putString("switch_state", "value");
//switch_state=editor.putBoolean(PIN_STATE, s2.isChecked());
editor.commit();
// Toast.makeText(getApplicationContext(), "Switch is ON", Toast.LENGTH_SHORT).show();
}
});
在Pattern_activity中:
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
s1.setChecked(sharedPreferences.getBoolean("toggleButton", false));
switch1= sharedPreferences.getBoolean(PIN_STATE, s1.isChecked() );
if (switch1== true)
{
s1.setEnabled(false);
Toast.makeText(getApplicationContext(), "PinService is ON, You can't Make PatternService ON", Toast.LENGTH_SHORT).show();
}
else
{
s1.setEnabled(true);
}
从那以后你可能需要为PATTERN_STATE
执行类似的操作,并且通常会理顺你的按钮状态,因为它们看起来有点混乱。