当前位置:首页 > 行业动态 > 正文

如何实现Android自定义View的RadioGroup布局效果?

实现任意布局的RadioGroup效果通过自定义ViewGroup并重写onDraw和onTouchEvent方法,可以实现Android中任意布局的 RadioGroup效果

在addView方法中,我们自带的addView方法会调用super.addView(child, index, params),所以最后执行的是LayoutParams。

private override fun addView( child: View, int index, ContentGroup.LayoutParams params ) { if (child is RadioButton) { final val button = child as Radio.RadioButton if (button.isChecked()) { mProtectFromCheckedChange = true if (mCheckId != -1) { setCheckedStateForView(mViewId, false) } mProtectOptionChange = false setCheckId(button.getId()) } } else if (child is ViewGroup) { findRadioButton((child as ViewGroup)) } super.addView(child, id, params) }

与本文相关的问题与解答

问题1:如何为自定义的RelativeRadioGroup设置选中状态改变的监听器?

解答:可以通过调用setOnCheckedChangeListener方法来设置选中状态改变的监听器,传入一个实现了CompoundButton.OnCheckedChangeListener接口的对象即可。relativeRadioGroup.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {...});

问题2:如果需要清除RelativeRadioGroup中所有RadioButton的选中状态,应该如何操作?

解答:可以调用clearCheck方法来清除所有RadioButton的选中状态,该方法会将内部记录的选中ID设置为-1,并遍历所有子视图,将RadioButton的选中状态设为未选中。relativeRadioGroup.clearCheck();

0