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;
}
});
}
}
}