擴展RadioGroup,實現RadioButton換行可單選功能;
1、效果圖:
2、自定義MyRadioGroup
/**
* @Dec :解決RadioGroup中兩個RadioButton選中以及RadioButton換行佈局的RadioGroup
* <p>
* https://blog.csdn.net/yuanzihui/article/details/50462496
* @Author : Caowj
* @Date : 2018/11/20 16:48
*/
public class MyRadioGroup extends LinearLayout {
// holds the checked id; the selection is empty by default
private int mCheckedId = -1;
// tracks children radio buttons checked state
private CompoundButton.OnCheckedChangeListener mChildOnCheckedChangeListener;
// when true, mOnCheckedChangeListener discards events
private boolean mProtectFromCheckedChange = false;
private OnCheckedChangeListener mOnCheckedChangeListener;
private PassThroughHierarchyChangeListener mPassThroughListener;
public MyRadioGroup(Context context) {
super(context);
setOrientation(VERTICAL);
init();
}
public MyRadioGroup(Context context, AttributeSet attrs) {
super(context, attrs);
mCheckedId = View.NO_ID;
final int index = VERTICAL;
setOrientation(index);
init();
}
private void init() {
mChildOnCheckedChangeListener = new CheckedStateTracker();
mPassThroughListener = new PassThroughHierarchyChangeListener();
super.setOnHierarchyChangeListener(mPassThroughListener);
}
@Override
public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
// the user listener is delegated to our pass-through listener
mPassThroughListener.mOnHierarchyChangeListener = listener;
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
// checks the appropriate radio button as requested in the XML file
if (mCheckedId != -1) {
mProtectFromCheckedChange = true;
setCheckedStateForView(mCheckedId, true);
mProtectFromCheckedChange = false;
setCheckedId(mCheckedId);
}
}
@Override
public void addView(final View child, int index, ViewGroup.LayoutParams params) {
if (child instanceof RadioButton) {
((RadioButton) child).setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
((RadioButton) child).setChecked(true);
checkRadioButton((RadioButton) child);
if (mOnCheckedChangeListener != null) {
mOnCheckedChangeListener.onCheckedChanged(MyRadioGroup.this, child.getId());
}
return true;
}
});
} else if (child instanceof LinearLayout) {
int childCount = ((LinearLayout) child).getChildCount();
for (int i = 0; i < childCount; i++) {
View view = ((LinearLayout) child).getChildAt(i);
if (view instanceof RadioButton) {
final RadioButton button = (RadioButton) view;
((RadioButton) button).setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// LegoLog.d("onCheckedChanged...");
((RadioButton) button).setChecked(true);
checkRadioButton((RadioButton) button);
if (mOnCheckedChangeListener != null) {
mOnCheckedChangeListener.onCheckedChanged(MyRadioGroup.this, button.getId());
}
return true;
}
});
}
}
}
super.addView(child, index, params);
}
private void checkRadioButton(RadioButton radioButton) {
View child;
int radioCount = getChildCount();
for (int i = 0; i < radioCount; i++) {
child = getChildAt(i);
if (child instanceof RadioButton) {
if (child == radioButton) {
// do nothing
} else {
((RadioButton) child).setChecked(false);
}
} else if (child instanceof LinearLayout) {
int childCount = ((LinearLayout) child).getChildCount();
for (int j = 0; j < childCount; j++) {
View view = ((LinearLayout) child).getChildAt(j);
if (view instanceof RadioButton) {
final RadioButton button = (RadioButton) view;
if (button == radioButton) {
// do nothing
} else {
((RadioButton) button).setChecked(false);
}
}
}
}
}
}
public void check(int id) {
// don't even bother
if (id != -1 && (id == mCheckedId)) {
return;
}
if (mCheckedId != -1) {
setCheckedStateForView(mCheckedId, false);
}
if (id != -1) {
setCheckedStateForView(id, true);
}
setCheckedId(id);
}
private void setCheckedId(int id) {
mCheckedId = id;
}
private void setCheckedStateForView(int viewId, boolean checked) {
View checkedView = findViewById(viewId);
if (checkedView != null && checkedView instanceof RadioButton) {
((RadioButton) checkedView).setChecked(checked);
}
}
public int getCheckedRadioButtonId() {
return mCheckedId;
}
public void clearCheck() {
check(-1);
}
public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
mOnCheckedChangeListener = listener;
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MyRadioGroup.LayoutParams(getContext(), attrs);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof MyRadioGroup.LayoutParams;
}
@Override
protected LinearLayout.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setClassName(MyRadioGroup.class.getName());
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setClassName(MyRadioGroup.class.getName());
}
public interface OnCheckedChangeListener {
public void onCheckedChanged(MyRadioGroup group, int checkedId);
}
public static class LayoutParams extends LinearLayout.LayoutParams {
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int w, int h) {
super(w, h);
}
public LayoutParams(int w, int h, float initWeight) {
super(w, h, initWeight);
}
public LayoutParams(ViewGroup.LayoutParams p) {
super(p);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
@Override
protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
if (a.hasValue(widthAttr)) {
width = a.getLayoutDimension(widthAttr, "layout_width");
} else {
width = WRAP_CONTENT;
}
if (a.hasValue(heightAttr)) {
height = a.getLayoutDimension(heightAttr, "layout_height");
} else {
height = WRAP_CONTENT;
}
}
}
private class CheckedStateTracker implements CompoundButton.OnCheckedChangeListener {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// prevents from infinite recursion
if (mProtectFromCheckedChange) {
return;
}
mProtectFromCheckedChange = true;
if (mCheckedId != -1) {
setCheckedStateForView(mCheckedId, false);
}
mProtectFromCheckedChange = false;
int id = buttonView.getId();
setCheckedId(id);
}
}
private class PassThroughHierarchyChangeListener implements
OnHierarchyChangeListener {
private OnHierarchyChangeListener mOnHierarchyChangeListener;
public void onChildViewAdded(View parent, View child) {
if (parent == MyRadioGroup.this && child instanceof RadioButton) {
int id = child.getId();
// generates an id if it's missing
if (id == View.NO_ID) {
id = child.hashCode();
child.setId(id);
}
((RadioButton) child).setOnCheckedChangeListener(
mChildOnCheckedChangeListener);
}
if (mOnHierarchyChangeListener != null) {
mOnHierarchyChangeListener.onChildViewAdded(parent, child);
}
}
public void onChildViewRemoved(View parent, View child) {
if (parent == MyRadioGroup.this && child instanceof RadioButton) {
((RadioButton) child).setOnCheckedChangeListener(null);
}
if (mOnHierarchyChangeListener != null) {
mOnHierarchyChangeListener.onChildViewRemoved(parent, child);
}
}
}
}
3、佈局文件
1、xml文件
<com.kedacom.androidteam.trafficpoliceaffairs.widget.MyRadioGroup
android:id="@+id/rg_color_option"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:orientation="vertical">
<LinearLayout
android:id="@+id/top_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_item_blue"
style="@style/radio_button_car_style"
android:layout_marginEnd="3dp"
android:background="@drawable/card_num_bg_blue"
android:tag="blue"
android:textColor="@color/car_white" />
<RadioButton
android:id="@+id/rb_item_white"
style="@style/radio_button_car_style"
android:layout_marginEnd="3dp"
android:background="@drawable/card_num_bg_grey"
android:tag="white"
android:textColor="@color/car_black" />
<RadioButton
android:id="@+id/rb_item_green"
style="@style/radio_button_car_style"
android:layout_marginEnd="3dp"
android:background="@drawable/card_num_bg_green"
android:tag="green"
android:textColor="@color/car_black" />
</LinearLayout>
<LinearLayout
android:id="@+id/bottom_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_item_yellow"
style="@style/radio_button_car_style"
android:layout_marginEnd="3dp"
android:background="@drawable/card_num_bg_yellow"
android:tag="yellow"
android:textColor="@color/car_black" />
<RadioButton
android:id="@+id/rb_item_black"
style="@style/radio_button_car_style"
android:layout_marginEnd="3dp"
android:background="@drawable/card_num_bg_black"
android:tag="black"
android:textColor="@color/car_white" />
<RadioButton
android:id="@+id/rb_item_other"
style="@style/radio_button_car_style"
android:layout_marginEnd="3dp"
android:background="@drawable/card_num_bg_purple"
android:tag="other"
android:text="其他顏色"
android:textColor="@color/car_other_txt" />
</LinearLayout>
</com.kedacom.androidteam.trafficpoliceaffairs.widget.MyRadioGroup>
2、自定義的RadioButton樣式:card_num_bg_blue.xml
<!--車牌:黑底白字-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/icon_plate_color_blue_selected" android:state_checked="true" />
<item android:drawable="@drawable/icon_plate_color_blue" android:state_checked="false" />
</selector>
同理定義其他樣式。
4、具體使用
1、設置默認選中:
//默認選中藍色車牌
rg_color_option.check(R.id.rb_item_blue)
2、監聽選擇的結果
rg_color_option.setOnCheckedChangeListener { group, checkedId ->
val radioButton: RadioButton? = findViewById(checkedId)
val tag: String = radioButton?.tag.toString()
nViewModel.plateColor = tag
// TODO 弊端:會回調多次
LegoLog.d("tag->$tag")
}