问题
In my App i want to open a dialog window with a radiogroup with some items (each item should be an activity ) the user can choose from. The chosen item/ID should get stored in the sharedpreferences. The ID load every App start and open the chosen item/activity.
Can someone tell me how to do that Please ?
回答1:
There are many samples but ok, I'll give an example:
You can define 2 methods under your activity:
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int selectedRadioID = sharedPreferences.getInt("SELECTED_RADIO", 0);
if(selectedRadioID > 0) {
// you got previously selected radio
RadioButton rb = (RadioButton)findViewById(selectedRadioID);
rb.setSelected(true);
}
}
private void savePreferences(String key, int radioId) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putInt(key, radioId);
editor.commit();
}
Use this methods on your activities onCreate
method.
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadSavedPreferences();
RadioGroup rg = findViewById(R.id.your_radio_group_over_your_radios);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
savePreferences("SELECTED_RADIO", checkedId);
}
});
}
You should improve this code, but this will give you the idea.
来源:https://stackoverflow.com/questions/19693817/android-store-radiogroup-id-in-sharedpreferences-and-load-it