Android store radiogroup id in sharedpreferences and load it

断了今生、忘了曾经 提交于 2019-12-12 05:29:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!