代码之家  ›  专栏  ›  技术社区  ›  Tawani

在Android中实现RadioButtonPreference

  •  4
  • Tawani  · 技术社区  · 15 年前

    如何实现 RadioButtonPreference 在Android中?就像 CheckBoxPreference .

    有什么解决办法吗?

    2 回复  |  直到 8 年前
        1
  •  6
  •   CommonsWare    15 年前

    使用A ListPreference .您需要有多个单选按钮才能使其有意义(否则,它只是一个复选框)。

    如果出于某种原因,您不想使用 列表首选项 ,将源代码抓取到 CheckBoxPreference 从android开放源码树和滚动您自己的偏好实现。然后,您应该能够使用名称空间(例如com.foo)在首选XML中列出自定义实现。 RadioButtonPreference )

        2
  •  0
  •   Gnzlt    8 年前

    您可以使用自定义类扩展自 CheckBoxPreference 这样地:

    public class RadioButtonPreference extends CheckBoxPreference {
    
        public RadioButtonPreference(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            setWidgetLayoutResource(R.layout.preference_widget_radiobutton);
        }
    
        public RadioButtonPreference(Context context, AttributeSet attrs) {
            super(context, attrs);
            setWidgetLayoutResource(R.layout.preference_widget_radiobutton);
        }
    
        public RadioButtonPreference(Context context) {
            this(context, null);
        }
    
        @Override
        public void onClick() {
            if (this.isChecked()) {
                return;
            }
            super.onClick();
        }
    }
    

    然后创建一个 preference_widget_radiobutton.xml 布局文件:

    <?xml version="1.0" encoding="utf-8"?>
    <!-- Layout used by CheckBoxPreference for the checkbox style. This is inflated
         inside android.R.layout.preference. -->
    <RadioButton android:id="@+android:id/checkbox"
                 xmlns:android="http://schemas.android.com/apk/res/android"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_gravity="center"
                 android:clickable="false"
                 android:focusable="false"/>