本文介绍了如何保存RadioGroup中的selectedIndex设置为共享preferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存radiogroupt共享preferences的selectedIndex但我不是如何做一个线索。任何人都可以给我一些提示,怎么办呢?谢谢

I'd like to save the selectedindex of a radiogroupt to sharedpreferences but I haven't a clue on how to do it. Can anyone give me some tips how to do it? THanks

推荐答案

试试下面的示例code:

Try the sample code below :

public class MainActivity extends Activity {

private RadioGroup radioGroup;

private static final String SELECTED_INDEX="SelectedIndex";

private OnCheckedChangeListener checkedChangedListener=new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        saveSelectedIndex(checkedId);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    radioGroup = (RadioGroup) findViewById(R.id.rg);
    radioGroup.setOnCheckedChangeListener(checkedChangedListener);
    RadioButton rbtn=((RadioButton)radioGroup.findViewById(getSelectedValue()));
    if(rbtn!=null){
        rbtn.setChecked(true);
    }
}

private int getSelectedValue(){
    SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this);
    return pref.getInt(SELECTED_INDEX, -1);
}

private void saveSelectedIndex(int value){
    SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(this).edit();
    editor.putInt(SELECTED_INDEX, value);
    editor.commit();
}

}

这篇关于如何保存RadioGroup中的selectedIndex设置为共享preferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 06:32