实现多行RadioGroup

Android中的RadioGroup只能横向或者纵向单行摆放。实现多行RadioGroup实际上是使用了多个RadioGroup,而同时只能有一个RadioGroup起作用。

原文地址http://www.tutorialforandroid.com/2009/11/select-radiobutton-from-multiple.html

Select a RadioButton from Multiple RadioGroup in Android


I bounds into  Radiogroup layout question  while trying out something in android. The problem is that you want a RadioButton but you don't want it to just be either horizontally placed or vertically placed which is the default way RadioGroup does. Say you want 2 rows of 4 RadioButton, by default you cant do this with one RadioGroup, so the solution is to make 2 RadioGroup but the problem now is that you need to handle both RadioGroup in turn that when one RadioButton is selected on one RadioGroup the other RadioGroup/s will deselect itself. To do this here is the code on how i did it (it has 3 RadioGroups), it might not be the best solution :)

private Boolean changeGroup = false;
public void onCheckedChanged(RadioGroup group, int checkedId){
  if (group != null && checkedId > -1 && changeGroup == false){
    if(group == frequencyGroup1){
      changeGroup = true;
      frequencyGroup2.clearCheck();
      frequencyGroup3.clearCheck();
      changeGroup = false;
    }else if(group == frequencyGroup2){
      changeGroup = true;
      frequencyGroup1.clearCheck();
      frequencyGroup3.clearCheck();
      changeGroup = false;
    }else if(group == frequencyGroup3){
      changeGroup = true;
      frequencyGroup1.clearCheck();
      frequencyGroup2.clearCheck();
      changeGroup = false;
    }
  }
}

Explanation
Create a flag stating that we mark as whether the function could be execute or not (see below)
private Boolean changeGroup = false;

On the default change function of RadioGroup, create a conditional statement that would execute the change function of all RadioGroup only when our flag state that it can execute the next code block. By default this function will execute when you select a RadioButton on a Group and/or when you call clearCheck() of each RadioGroup, and you may not want to do that especially when we call clearCheck.
if (group != null && checkedId > -1 && changeGroup == false){

The following code will just set the flag to true when users select a RadioButton on any group, thus when other RadioGroup call clearCheck() the code block in the function will not be called.
.....

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值