How to implement SharedPreferences with RadioButtons in Android

前端 未结 2 728
北海茫月
北海茫月 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:36

    What i can guide is that on checkedchanged event you can either get or put values in your shared pref. e.g

                     if(radio1 is checked)
                    {
                    sharedPref.putString(...);  //puts values in pref
                    sharedPref.commit();}
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题