gpt4 book ai didi

android - 如何从另一个类访问共享首选项 bool 值

转载 作者:太空狗 更新时间:2023-10-29 15:39:14 26 4
gpt4 key购买 nike

我创建了一个包含两个按钮的单选按钮组,我可以选择一个并保存它,它工作正常,关闭应用程序后仍然保存。我想要做的是在另一个类中使用单选按钮的值。这是我的设置类,其中包含共享首选项代码:

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 和开发人员文档,但我似乎无法找到如何做到这一点,欢迎任何建议。

谢谢

最佳答案

您需要再次访问 SharedPreferences,而不是 if(rb0 = true)(应该是 ==)。引自 http://developer.android.com/guide/topics/data/data-storage.html :

To read values, use SharedPreferences methods such as getBoolean() and getString().

所以你会使用类似的东西:

String settingsTAG = "AppNameSettings";
SharedPreferences prefs = getSharedPreferences(settingsTAG, 0);
boolean rb0 = prefs.getBoolean("rb0", false);
if(rb0 == true){
// Do something
}

关于android - 如何从另一个类访问共享首选项 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10606237/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com