android 怎么实现两组互斥的RadioGroup

时间无多,大概说说就不上图了。

大家知道,RadioGroup里的所有RadioButton是互斥的,但是有时候想要实现两组RadioGroup,并且这两组也互斥。怎么做呢?

首先说错误的做法吧:

1.如果你的RadioButton是通过继承的方法来做的,并在继承RadioButton的MyRadioButton里重写isChecked方法,再进行逻辑判断来区别是哪组RadioGroup,那一定会产生让你抓狂的错误。我这么做了好多次,终于发现问题所在:你构造函数初始化的时候(执行super(content)时)会调用一次ischecked方法,你点击某一个RadioButton的时候会调用4次ischecked方法!你可以自己在这个方法里用log.v输出就明白了,具体它为什么这样执行我也不知道,希望高手解答。

2.如果你使用RadioGroup的setOnCheckedChangeListener监听器来进行判断,请注意,你在任何时候修改某个RadioButton的状态都会调用这个方法。所以,如果你在这个监听器里进行逻辑判断,然后想把之前选中的RadioButton给设置成不选中,它会之前RadioButton所属RadioGroup的监听器的方法,也会出现让人困惑的现象。

radiogroup.setOnCheckedChangeListener(new OnCheckedChangeListener() 
	    {
	        public void onCheckedChanged(RadioGroup group, int checkedId) {
	            MyRadioButton now=(MyRadioButton)findViewById(checkedId);
	        	if(Checked_Id!=0)
	        	{
		            MyRadioButton previous=(MyRadioButton)findViewById(Checked_Id);
		            if(previous.type!=now.type)
		            {
		            	switch(previous.type)
		            	{
		            	case My:
		            		try
		            		{
		            		mygroup.clearCheck();
		            		}catch(Exception e){}
		            		break;
		            	case Server:
		            		try
		            		{
		            		servergroup.clearCheck();
		            		}catch(Exception e){}
		            		break;
		            	}
		            }
	        	}
	            Checked_Id=checkedId;
	            Checked_Name=now.getText().toString();
	        }
	    });
说明 :我的MyRadioButton是继承自RadioButton的。里面有一个我用来区别属于不同RadioGroup的枚举变量,MyRadioButton.type,它有My和Server两种值。(有朋友可能会说,不能直接从RadioButton里调用某个方法返回它所属的RadioGroup吗?不好意思,我没找到,找到的话告诉我!)Cheked_Id保存之前选中的RadioButton的id。mygroup和servergroup分别是我的radiogroup

当发现之前RadioButton和当前的type不一样时,就调用RadioGroup.clearCheck()方法来清空该RadioGroup选中的。

刚学习,写得很烂,如果有好方法实现两组互斥的RadioGroup的朋友请告诉我!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值