问题
There are a lot of questions on SO about saving radio buttons state in Shared Preferences but none of them provide the solution that I'm looking for.
I'm creating 15 radio groups and 4 radio buttons inside each radio group in a for loop. The radio groups have unique id from 1 to 15 and the radio buttons have ids ranging from 100 to 159.
This is the code I use to save radio buttons id:
public void saveArray(int[] array, String arrayName) {
SharedPreferences prefs = getActivity().getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++) {
editor.putInt(arrayName + "_" + i, array[i]);
}
editor.commit();
}
array
contains the unique ID of all those radio buttons that are checked and I've tested the above code, it works perfectly but the problem is I can't access it.
This is the code I use to retrieve radio button id:
public void loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
int array[] = new int[size];
for(int i=0;i<size;i++) {
array[i] = prefs.getInt(arrayName + "_" + i, 0);
}
}
Like saveArray
, loadArray
also works. The array is populated by the correct radio button ids.
The problem starts now - I can't access those radio buttons, I can't do findViewById()
because that is only available in onCreateView()
So this will not work inside loadArray
for(int i=0; i<size; i++) {
RadioButton radio1 = (RadioButton) findViewById(array[i]);
}
The possible solution to findViewById
is storing the views in onCreateView()
and then accessing it later. So I created a Radio Button array
RadioButton[] allRadio = new RadioButton[15];
Now inside onCheckedChanged
, I'm adding the selected radio buttons to the array:
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton radio = (RadioButton) rootView.findViewById(i);
String selectedValue = radio.getText().toString();
allRadio[radioGroup.getId()-1] = radio;
}
The above code perfectly stores the radio buttons inside the array but now I can't save them! You can store int, string etc.. in Shared Preferences but not radio buttons! The solution to this could be to store radio button id but then the same problem will start all over again that findViewById()
is not available.
回答1:
public void loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
int array[] = new int[size];
for(int i=0;i<size;i++) {
array[i] = prefs.getInt(arrayName + "_" + i, 0);
//->put Toast here and check whether your are getting the id's or not. If you
//->are getting it, return arrays of id back to calling method
}
}
来源:https://stackoverflow.com/questions/38257874/how-to-store-and-access-radio-buttons-from-shared-preferences