How to implement SharedPreferences with RadioButtons in Android
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:
Each category has a number of options. Each option has two Strings to denote the option's name and its config开发者_Python百科uration information. The user selects an option by tapping on the radio button. There should be two radio groups: one for each category. The image doesn't show it, but there should be "save" and "cancel" buttons at the bottom of the screen.
For the layout, I called getAll in order to display the key and value (which are just TextViews). This is where I'm lost.
- I don't know how to link the Preference with a RadioButton.
- I don't know how to save the changes (because I don't know how to link the Preference to a RadioButton).
- I'd also like to implement something like a dirty bit to denote whether there was really a change before saving, but I don't know what the Android best practice for this is.
As you can see, I'm completely lost. So, any help would be really, greatly appreciated.
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.
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();}
精彩评论