2

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

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

谢谢

4

2 回答 2

10

您需要再次访问 SharedPreferences而不是if(rb0 = true)(无论如何都应该如此)。==引自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
}
于 2012-05-15T18:00:21.607 回答
2

您还可以使用:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.getBoolean("myKey", false)
于 2015-12-23T19:06:58.837 回答