RadioGroup和RadioButton在APP开发中是经常使用的组件,常见的应用场景比如一排菜单,点击菜单跳转不同的界面,或者界面中的单选,比如选择性别。
使用起来也很简单,不过在实际开发过程中,我意外发现一个问题,看代码,这里为了简化问题,就用一个简单的选择性别为例:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
</pre><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <RadioGroup android:id="@+id/radio_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:checkedButton="@+id/male" android:orientation="horizontal" android:layout_alignParentBottom="true" > <RadioButton android:id="@+id/male" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:checked="true" android:text="男" /> <RadioButton android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="女" /> <RadioButton android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="人妖" /> </RadioGroup></RelativeLayout><pre name="code" class="html">
这个功能很简单,就是在界面的底部有一排单选,默认选中“男”,用户可以点击选择任意一个,始终只会有一个被选中,表面上看没有什么问题,但如果操作步骤如下就会有问题了:
进入界面后,默认是“男”选中,这时,继续用一个手指按中已选中的“男”,不要松开,完后用第二个手指按中“女”,完后抬起第二个手指(第一个手指还继续按着“男”),这时会发现,现在变为“女”选中了,最后松开第一个手指 ,又重新变为“男”选中。
也就是说,在手指还按着“男”的时候,竟然还可以同时去按别的选项,并且选中状态改变了,这种用户体验肯定是不好的,感觉会很奇怪。(需要说明的是,如果将RadioGroup改成默认的垂直方向,是没有这个问题的)
下面来着手解决这个问题,既然一个手指按下一个选项时,不希望其它的选项再响应其它按下的事件,那么就在按下一个选项时禁用其它的选项好了
首先定义一个变量curPress,默认值-1,它用来记录当前正在按的选项(同一个时刻只能有一个)的ID,当手指按下时,记录按下的选项的ID,同时将其它选项的enable设置为false,即不可用,而在手指抬起时,将curPress的值重新赋值为-1,同时将其它选项的enable设置为true,即这时可以再去按其它选项了。修改后的代码如下,界面不变
public class MainActivity extends Activity {
RadioGroup group;
int curPress = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group = (RadioGroup) findViewById(R.id.radio_group);
for (int i = 0; i < group.getChildCount(); i++) {
final RadioButton menu = (RadioButton) group.getChildAt(i);
menu.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
curPress = menu.getId();
for (int j = 0; j < group.getChildCount(); j++) {
if (curPress != group.getChildAt(j).getId()) {
group.getChildAt(j).setEnabled(false);
}
}
break;
case MotionEvent.ACTION_UP:
for (int j = 0; j < group.getChildCount(); j++) {
if (curPress != group.getChildAt(j).getId()) {
group.getChildAt(j).setEnabled(true);
}
}
curPress = -1;
break;
}
return false;
}
});
}
}
}