我在RadioGroup中有两个性别的RadioButtons
1)男
2)女性
我希望将它存储在sharedpreferences中,并在我再次打开它时检索它。
我想在共享偏好中保存微调器,我怎样才能保存它。
答案 0 :(得分:0)
// Try this way,hope this will help you...
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<RadioGroup
android:id="@+id/rdgGender"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/rdbMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"/>
<RadioButton
android:id="@+id/rdbFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"/>
</RadioGroup>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity{
private RadioGroup rdgGender;
private RadioButton rdbMale;
private RadioButton rdbFemale;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rdgGender = (RadioGroup) findViewById(R.id.rdgGender);
rdbMale = (RadioButton) findViewById(R.id.rdbMale);
rdbFemale = (RadioButton) findViewById(R.id.rdbFemale);
rdgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
switch (checkedId){
case R.id.rdbMale:
editor.putInt("genderValue", R.id.rdbMale);
break;
case R.id.rdbFemale:
editor.putInt("genderValue",R.id.rdbFemale);
break;
}
editor.commit();
}
});
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE);
switch (sharedPreferences.getInt("genderValue",R.id.rdbMale)){
case R.id.rdbMale:
rdbMale.setChecked(true);
break;
case R.id.rdbFemale:
rdbFemale.setChecked(true);
break;
}
}
}