我创建了一个包含两个按钮的广播组,我可以选择一个并保存它,它工作正常,在关闭应用程序后仍然存储。我想要做的是使用另一个类中的单选按钮的值。这是我的设置类,其中包含共享首选项代码:
public class Settings extends Activity {
private String settingsTAG = "AppNameSettings";
private SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
prefs = getSharedPreferences(settingsTAG, 0);
final RadioButton rb0 = (RadioButton) findViewById(R.id.radioInternetYes);
final RadioButton rb1 = (RadioButton) findViewById(R.id.radioInternetNo);
rb0.setChecked(prefs.getBoolean("rb0", true));
rb1.setChecked(prefs.getBoolean("rb1", false));
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
prefs = getSharedPreferences(settingsTAG, 0);
Editor editor = prefs.edit();
editor.putBoolean("rb0", rb0.isChecked());
editor.putBoolean("rb1", rb1.isChecked());
editor.commit();
finish();
}
} );
}
在另一个课程中,我试图在点击按钮时检查rb0是真还是假:
share.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if(rb0 = true){
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{""});
i.putExtra(Intent.EXTRA_SUBJECT, "Check out my awesome score!");
i.putExtra(Intent.EXTRA_TEXT , "I am playing this awesome game called Tap the Button, and I just scored the incredible highscore of " +s+ " Taps!!\n\nCan you beat it!?");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(FailScreen.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
else{
//Display warning that rb0 is false
}
}
});
我已经研究过Stackoverflow和开发人员文档,但我似乎无法知道如何做到这一点,任何建议都表示赞赏。
谢谢
答案 0 :(得分:9)
而不是if(rb0 = true)
(反正应该是==
),您需要再次访问SharedPreferences。引自http://developer.android.com/guide/topics/data/data-storage.html:
要读取值,请使用SharedPreferences方法,例如getBoolean()和 的getString()。
所以你会使用类似的东西:
String settingsTAG = "AppNameSettings";
SharedPreferences prefs = getSharedPreferences(settingsTAG, 0);
boolean rb0 = prefs.getBoolean("rb0", false);
if(rb0 == true){
// Do something
}
答案 1 :(得分:2)
您也可以使用:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.getBoolean("myKey", false)