2

2つのボタンを含むラジオグループを作成しました。1つを選択して保存できます。正常に機能し、アプリを閉じた後も保存されます。私がやりたいのは、別のクラスのラジオボタンの値を使用することです。共有設定コードを含む私の設定クラスは次のとおりです。

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がtrueかfalseかを確認しようとしています。

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

if(rb0 = true)(とにかくそうあるべきです)の代わりに==、SharedPreferences に再度アクセスする必要があります。http://developer.android.com/guide/topics/data/data-storage.htmlから引用:

値を読み取るには、getBoolean() や getString() などの SharedPreferences メソッドを使用します。

したがって、次のようなものを使用します。

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 に答える