我想拥有这样的功能 - 我有一个对话框(带有设置),其中有一个带有两个 RadioButtons 的 RadioGroup。当我使用“保存”按钮关闭对话框时,我不仅希望将数据保存在我的 Data 类中,而且我希望对话框在下次打开时打开保存的设置。我尝试使用 RadiGroup 方法来实现这一点:getCheckedRadioButtonId() 和 .check(int),但我的解决方案不起作用,我不知道为什么。
我的代码:
SettingsDialogFragment.java
public class SettingsDialogFragment extends DialogFragment{
private boolean ifMale;
private int checkedRadio;
private RadioGroup rg;
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.settings);
View view = LayoutInflater.from(getActivity()).inflate(R.layout.settings_dialog, null);
builder.setView(view);
builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Data.ifMale = ifMale;
checkedRadio = rg.getCheckedRadioButtonId();
System.out.println("numer radio" +checkedRadio);
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
rg = (RadioGroup) view.findViewById(R.id.radio_group);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId) {
case R.id.radio_female:
//Log.v("RadioGroup", "female");
ifMale = false;
break;
case R.id.radio_male:
Log.v("RadioGroup","male");
ifMale = true;
break;
}
}
});
rg.check(checkedRadio);
return builder.create();
}
}
settings_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioGroup android:id="@+id/radio_group"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<RadioButton android:id="@+id/radio_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/female"/>
<RadioButton android:id="@+id/radio_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/male"/>
</RadioGroup>
</LinearLayout>