没有可用的开箱即用的RadioGroup首选项。您需要通过扩展DialogPreference类来编写一个。
使用对话框内容创建单独的布局文件(/res/layout/pref_radiogroup.xml)。
<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RadioGroup
android:id="@+id/radioSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/radio_male" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radio_female" />
</RadioGroup>
</FrameLayout>
创建您的RadioGroupPreference类,它将扩展DialogPreference。
public class RadioGroupPreference extends DialogPreference {
private RadioGroup radioGroup;
public RadioGroupPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.pref_radiogroup);
}
@Override
protected View onCreateDialogView() {
View root = super.onCreateDialogView();
radioGroup = (RadioGroup) root.findViewById(R.id.radioSex);
return root;
}
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
setSelectedValue(getPersistedString("Male"));
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (!positiveResult) {
return;
}
if (shouldPersist()) {
String valueToPersist = getSelectedValue();
if (callChangeListener(valueToPersist)) {
persistString(valueToPersist);
}
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
private void setSelectedValue(String value) {
for (int i = 0; i < radioGroup.getChildCount(); i++) {
View view = radioGroup.getChildAt(i);
if (view instanceof RadioButton) {
RadioButton radioButton = (RadioButton) view;
if (radioButton.getText().equals(value)) {
radioButton.setChecked(true);
}
}
}
}
private String getSelectedValue() {
int radioButtonId = radioGroup.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) radioGroup.findViewById(radioButtonId);
return (String) radioButton.getText();
}
}
现在您只需将自定义首选项添加到您的首选项屏幕即可。
<com.package.RadioGroupPreference
android:summary="Radio Group Preference Summary"
android:title="Radio Group Preference"
android:key="preference_key"
android:defaultValue="@string/radio_male" />
对不起,我不明白。我应该怎么做?你可能会更精确,甚至可能会把示例代码? –
我刚刚编辑了我的答案并添加了一个代码示例。 –