How to implement SharedPreferences with RadioButtons in Android

前端 未结 2 733
北海茫月
北海茫月 2021-01-25 07:50

I\'m a newb to Android, so please be patient.

I\'m trying to set up a new app and it needs to look like this:

2条回答
  •  走了就别回头了
    2021-01-25 08:52

    I assume you're creating your own Activity with your own layout. In this case you won't have access to the automated preference loading and saving mechanisms provided by PreferenceActivity.

    You will have to de everything by hand: in the onCreate() you should add an event listener to Cancel and Save buttons:

    Button saveButton = (Button)findViewById(R.id.saveButton);
    saveButton.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
          save();
       }
    });
    

    In the save() method you have to request selection state from the radio buttons, and store your selections in the shared preferences:

    private void save() {
       String prefValue = (RadioButton)findViewById(R.id.firstButton).isChecked()?"First string":"Second string";
       SharedPreferences pref = PreferencesManager.getDefaultSharedPreference(this);
       pref.edit().putString("PrefName", prefValue).commit();
    }
    

    For the "dirty bit", there are two solutions: you add a click listener to the radio buttons, and if any of them is clicked, you say dirty. Or you can add those listeners, and request the current selections, and decide if it is different from the initial state.

    The other way would be to create a PreferencesActivity, with a preferences.xml where you can specify which keys and values to store for a selected item.

提交回复
热议问题