您的位置:首页 > 移动开发 > Android开发

Android RadioButton连续响应选中事件

2017-09-27 15:55 411 查看
多个button中只能选择一个,那么RadioButton+RadioGroup是一个很好的选择.比如在空调在工作模式上只能有一个选择,那么用radioButton是个很不错的选择。



但这样会有一个问题–如果别人将空调设置暖风,心情不爽的用户肯定会抓住机会再次点击冷风(自习室抢空调的日常)。这时用户就会惊奇的发现,不管他怎么点击,都没反应。为什么没反应,为什么没反应!因为程序猿用的是RadioButton!选中之后的radioButton,再次点击该按钮不会触发OnCheckedChangeListener.onCheckedChanged事件,这一点也反映在了该事件监听器的命名上。

这时候应该把radioButton控件换成Button,OnCheckedChangeListener改成OnClickListener吗?No,No,仔细一想,改成Button之后依然很麻烦,因为Button不具备某一组Button只能选中一个的功能,你必须自己维护Button的分组,而且选中一个button后重置上一个被选中的button的状态。更不用说在布局文件中的改动了。如果涉及的页面比较多,那么恭喜你,准备吃免费的加班餐吧。

更可怕的是,如果项目经理在不远的将来突然对你说,我们目前需要根据设备的当前状态实时的重置按钮的选中状态,为了减少后台的开销,按钮不能连续选中。这意味着你需要改回去,是不是很酸爽,哈哈。

大丈夫,大丈夫,让我们用苏格拉底的方式来思考这样一个问题,为什么用户会知道某个radioButton被选中了?因为背景色被改变了呀。那么可以代码设置背景色和radioButton的选中状态吗?当然可以。那么我可以在响应选中事件之后,代码将选中的radioButton置为未选中的状态,然后将背景色设置为选中色,这样就可以被再次选中了,而且对于用户来说,操作体验是不会变化的,因为用户能观察到的只是view层。

ok,上代码。

mModeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
switch (checkedId){
//相关操作
}
//this 代表的是OnCheckedChangeListener对象
RadioButtonRestoreUtils.restoredRadioButton(checkedId,group,this,MainActivity.this);
}
});```
RadioButtonRestoreUtils是我封装的一个类,方便在其他的类中使用。上代码


public class RadioButtonRestoreUtils {

public static void restoredRadioButton(@IdRes int checkedId, RadioGroup radioGroup, RadioGroup.OnCheckedChangeListener listener, Context mContext) {

radioGroup.setOnCheckedChangeListener(null);//checked监听事件失效

RadioButton radioButton = (RadioButton) radioGroup.findViewById(checkedId);
//清除radioButton的选中状态,只保留背景色
radioButton.setClickable(true);
radioButton.setChecked(false);
int childCount = radioGroup.getChildCount();
RadioButton childAt = null;
//将所有radioButton背景色置为未选中状态,目的是清除之前的设置
for (int i = 0; i < childCount; i++) {
childAt = (RadioButton) radioGroup.getChildAt(i);
childAt.setBackgroundResource(R.drawable.ih_airconditioner_tv_normal);
childAt.setTextColor(mContext.getResources().getColor(R.color.device_text_color_normal));
}
//将之前选中的radioButton背景色设为选中状态
radioButton.setBackgroundResource(R.drawable.ih_airconditioner_tv_focused);
radioButton.setTextColor(mContext.getResources().getColor(R.color.device_text_color_focus));
radioGroup.setOnCheckedChangeListener(listener);//重新添加
}


}

“`

radioGroup.setOnCheckedChangeListener(null);这段代码很重要,因为radioButton.setChecked(false);方法会再次触发OnCheckedChangeListener.onCheckedChanged事件。我们可以先将RadioGroup的监听事件保存下来(即restoredRadioButton方法中的参数this),同时将其监听事件置空,修改完radioButton的状态后,再重新赋值。就算项目经理以后取消了连续选择需求,我们只需要让restoredRadioButton这个方法什么都不做就OK了,是不是很炫酷,哈哈哈。

其实,个人认为最好是自定义一个RadioGroup和RadioButton,这样可以更加完美的应对需求变化。希望我在国庆期间可以想起来这件事情。

源码下载

有用的话,麻烦各位看官点个赞<3<3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息