需求场景举例:新增地址中地址标签属性 家/学校/公司 三选一 点击选中的取消选择
实现方式:继承AppCompatRadioButton,重写toggle方法。上代码:
public class XXXButton extends AppCompatRadioButton {
public XXXButton (Context context) {
this(context, null);
}
public XXXButton (Context context, AttributeSet attrs) {
this(context, attrs, R.attr.radioButtonStyle);
}
public XXXButton (Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void toggle() {
setChecked(!isChecked());
if (!isChecked()) {
((RadioGroup) getParent()).clearCheck();
}
}
}
xml使用
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_toEndOf="@+id/bq"
android:layout_centerVertical="true"
android:orientation="horizontal">
<com.a.b.XXXButton
android:id="@+id/rb_home"
android:layout_width="wrap_content"
android:layout_height="24dp"
android:background="@drawable/comment_stu_bg"
android:button="@null"
android:gravity="center"
android:minWidth="50dp"
android:text="家"
android:textColor="@drawable/comment_stu_tv_bg"
android:textSize="13sp" />
<com.a.b.XXXButton
android:id="@+id/rb_company"
android:layout_width="wrap_content"
android:layout_height="24dp"
android:layout_marginStart="15dp"
android:background="@drawable/comment_stu_bg"
android:button="@null"
android:gravity="center"
android:minWidth="50dp"
android:text="公司"
android:textColor="@drawable/comment_stu_tv_bg"
android:textSize="13sp" />
<com.a.b.XXXButton
android:id="@+id/rb_school"
android:layout_width="wrap_content"
android:layout_height="24dp"
android:layout_marginStart="15dp"
android:background="@drawable/comment_stu_bg"
android:button="@null"
android:gravity="center"
android:minWidth="50dp"
android:text="学校"
android:textColor="@drawable/comment_stu_tv_bg"
android:textSize="13sp" />
</RadioGroup>
Activity中监听
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_home:
lable = 0;
break;
case R.id.rb_company:
lable = 1;
break;
case R.id.rb_school:
lable = 2;
break;
default:
lable = -1;
break;
}
}
});
over
网友评论