Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android CheckBox 深入實踐:資料驅動狀態、列表復用加鎖與自造篩選器

編輯:關於 Android 程式設計

0 與 1 是整個電腦世界的地基,在數理邏輯裡它們代表真與假。看似簡單的兩個值,變化卻無窮。今天要聊的,就是 Android 控件家族裡最具這種「二元魔力」的成員——CheckBox。

一、最基礎的用法

先在 XML 中宣告:

 <?xml version="1.0" encoding="utf-8"?> <CheckBox xmlns:android="https://schemas.android.com/apk/res/android" android:id="@+id/cbx" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" /> 

接著在 Activity 中掛上監聽:

 CheckBox cbx = (CheckBox) findViewById(R.id.cbx); cbx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //do something } }); 

二、關鍵觀念:讓資料控制視圖

CheckBox 本質上是一個「展示用的視圖」,因此正確的心態是用資料去驅動它的呈現,而不是反過來。而且監聽器一定要在 setChecked 之前設定,否則資料無法有效反映到介面上。

 boolean isChecked= false; CheckBox cbx = (CheckBox) findViewById(R.id.cbx); cbx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ //do something }else{ //do something else } } }); cbx.setChecked(isChecked); 

三、進階場景:CheckBox 遇上 ListView / RecyclerView

這裡才是真正的難題。列表中的視圖數量遠小於資料筆數,因為螢幕上的 View 會被反覆複用。如果你不用資料來記錄狀態,就會出現經典靈異事件:只勾了第一筆,往上滾動後下面的項目竟然也變成勾選狀態。

直覺的修法是在 getView / onBindViewHolder 中同步狀態:

 holder.cbx.setTag(item); holder.cbx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Item item =(Item) buttonView.getTag(); if(isChecked){ item.setCheckState(true); //do something }else{ item.setCheckState(false); //do something else } } }); cbx.setChecked(item.getCheckState()); 

這寫法基本可行,但代價是在每筆資料裡塞一個狀態欄位——既多餘,又會讓本地資料結構與伺服器不一致。更合理的認知是:勾選狀態屬於列表,而不是屬於項目本身。Android 為此準備了 SparseArray / SparseBooleanArray,實務上我最常用 SparseBooleanArray。

 private class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{ SparseBooleanArray mCheckStates=new SparseBooleanArray(); @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //... } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { holder.cbx.setTag(position); holder.cbx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int pos =(int)buttonView.getTag(); if(isChecked){ mCheckStates.put(pos,true); //do something }else{ mCheckStates.delete(pos); //do something else } } }); cbx.setChecked(mCheckStates.get(position,false)); } @Override public int getItemCount() { //... } } 

如此一來列表顯示就正常了,勾選時也會自動回呼 onCheckedChanged 去更新 mCheckStates。若想用程式主動勾選某項:

 mCheckStates.put(pos,true); adapter.notifyDatasetChanged(); 

反過來,要取出所有被勾選的項目更是輕鬆:

 ArrayList<Item> selItems=new ArrayList<>(); for(int i=0;i < mCheckStates.size();i++){ if(mCheckStates.valueAt(i)){ selItems.add(allItems.get(mCheckStates.keyAt(i))); } } 

四、兩個容易忽略的細節:加鎖與去重

CheckBox 太「敏感」了——即使設成 disabled,它依然點得動,onCheckedChanged 照樣觸發。最直覺的補救是在回呼裡把狀態翻回去:

 holder.cbx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { buttonView.setChecked(!isChecked); //... } }); 

但這會再次觸發 onCheckedChanged,形成死循環。因此凡是「在回呼內用 cbx 自己改狀態」,一定要加鎖:

 boolean lockState=false; holder.cbx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(lockState)return; //不然cbx改變狀態. lockState=true; buttonView.setChecked(!isChecked); lockState=false; //... } }); 

加鎖技巧在實務上很常用,例如回呼裡發了網路請求,而請求結果又要回頭更新勾選狀態時,就得靠 lockState 直接改 cbx,才能讓它與 mCheckStates 保持一致。

另一個坑是重複觸發:如果 isChecked 與 mCheckStates.get(pos) 相同,//do something 就會被執行兩次。若這段邏輯是網路請求,麻煩就大了,所以記得加上過濾。

 @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(lockState)return; int pos =(int)buttonView.getTag(); if(mCheckStates.get(pos,false) == isChecked)return; if(isChecked){ mCheckStates.put(pos,true); //do something }else{ mCheckStates.delete(pos); //do something else } } 

五、用 CheckBox + PopupWindow 自造列表篩選器

能聯用 SparseBooleanArray、又記得加鎖與去重,代表你 CheckBox 的基本功已經到位。接下來才是真正有趣的部分。

列表能上下滑動只是及格線。當項目一多,產品通常會要求篩選功能,而常見做法是 Spinner——但系統 Spinner 擴展性差又不美觀,於是很多人乾脆不用。這裡分享一套我自己想出來的機制:把 CheckBox 當成篩選器入口,用 PopupWindow 承載選項。

原理:為 CheckBox 掛上監聽,isChecked 分支負責彈出 PopupWindow;!isChecked 分支則讀取 PopupWindow 回寫的結果,用新條件刷新列表。

MainActivity:

 public class MainActivity extends AppCompatActivity { String[] filter_type_strs = {"音樂", "書籍", "電影"}; CheckBox cbx; private boolean lockState=false; int current_filter_type=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cbx = (CheckBox) findViewById(R.id.cbx); cbx.setText(filter_type_strs[current_filter_type]); cbx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (lockState) return; try { if (isChecked) { //此處傳入了cbx做參數 PopupWindow pw = new FilterLinePw(buttonView.getContext(), cbx, filter_type_strs); pw.showAsDropDown(cbx); } else { //此處的buttonView就是cbx Integer pos = (Integer) buttonView.getTag(); if (pos == null || pos == -1) return; current_filter_type = pos; Toast.makeText(MainActivity.this, "搜索"+filter_type_strs[current_filter_type], Toast.LENGTH_SHORT).show(); } } catch (NullPointerException e) { //以防萬一 lockState = true; buttonView.setChecked(!isChecked); lockState = false; } } }); } } 

FilterLinePw:

 public class FilterLinePw extends PopupWindow { RadioGroup radioGroup; CheckBox outCbx; //為動態生成radioButton生成id int[] rbtIds = {0, 1, 2}; public FilterLinePw(Context context, CheckBox outCbx, String[] items) { super(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); View contentview = LayoutInflater.from(context).inflate(R.layout.filter_line_popupwindow, null); setContentView(contentview); setFocusable(true); setOutsideTouchable(true); this.outCbx = outCbx; contentview.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { dismiss(); return true; } return false; } }); contentview.setFocusable(true); // 這個很重要 contentview.setFocusableInTouchMode(true); contentview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); init(context, contentview,items); } private void init(Context context, View contentview, String[] items) { /** * 用傳入的篩選條件初始化UI */ radioGroup = (RadioGroup) contentview.findViewById(R.id.filter_layout); radioGroup.clearCheck(); if (items == null) return; for (int i = 0; i < items.length; i++) { RadioButton radioButton = (RadioButton) LayoutInflater.from(context).inflate(R.layout.line_popupwindow_rbt, null); radioButton.setId(rbtIds[i]); radioButton.setText(items[i]); radioGroup.addView(radioButton, -1, radioGroup.getLayoutParams()); if (items[i].equals(outCbx.getText())) { outCbx.setTag(i); radioButton.setChecked(true); } } radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { dismiss(); } }); } //重點內容,重寫dismiss(); @Override public void dismiss() { if (outCbx != null && outCbx.isChecked()) { int id = radioGroup.getCheckedRadioButtonId(); RadioButton rbt = (RadioButton) radioGroup.findViewById(id); Integer old_tag = (Integer) outCbx.getTag(); if (old_tag == null) { super.dismiss(); return; } if (old_tag != id) { outCbx.setTag(id); outCbx.setText(rbt.getText()); } else { outCbx.setTag(-1); } //下面執行之後,會執行MainActivity中的onCheckedChanged裡的否定分支 outCbx.setChecked(false); } super.dismiss(); } } 

流程小結:使用者點擊 MainActivity 的 CheckBox → 進入 isChecked 分支 → PopupWindow 彈出,操作環境切換到彈窗內 → 使用者選好條件 → PopupWindow 把結果寫進 outCbx 並切換其狀態 → 觸發 MainActivity 的否定分支(範例是 Toast,實務可換成網路請求)→ 最後執行 super.dismiss() 關閉彈窗。由於 PopupWindow 的程式並未阻塞後續流程,Activity 端完全不必操心關閉時機;再加上 try-catch 保底,整體相當穩健。這套機制把篩選邏輯從 Activity 中徹底剝離,讓篩選元件得以獨立復用,是很軟體工程的拆法。

六、私房菜:用 TouchDelegate 擴大點擊熱區

CheckBox 繼承自 TextView,而 button 屬性指定的圖示通常偏小,導致可點擊區域也小、手指常常戳不到。解法是用 TouchDelegate 把觸控範圍撐大:

 public class FrameLayoutCheckBox extends FrameLayout { CompoundButton cbx; public FrameLayoutCheckBox(Context context) { super(context); } public FrameLayoutCheckBox(Context context, AttributeSet attrs) { super(context, attrs); } public FrameLayoutCheckBox(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } private CheckBox findCheckBox(View view) { //無遞歸廣度優先遍歷尋找CheckBox - -!我只是想重溫一下C ArrayList<View> views = new ArrayList<>(); views.add(view); while (!views.isEmpty()) { View c = views.remove(0); if (c instanceof CheckBox) { return (CheckBox) c; } else if (c instanceof ViewGroup) { ViewGroup fa = (ViewGroup) c; for (int i = 0; i < fa.getChildCount(); i++) { views.add(fa.getChildAt(i)); } } } return null; } @Override protected void onFinishInflate() { super.onFinishInflate(); if (getChildCount() > 0) { View child = findCheckBox(this); if (child instanceof CompoundButton) cbx = (CompoundButton) child; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (cbx != null) { Rect bounds = new Rect(getPaddingLeft(), getPaddingTop(), getPaddingLeft() + getMeasuredWidth() + getPaddingRight(), getPaddingTop() + getMeasuredHeight() + getPaddingBottom()); TouchDelegate delegate = new TouchDelegate(bounds, cbx); setTouchDelegate(delegate); } } } 

把 CheckBox 放進這個自訂 FrameLayout 裡,點擊範圍就等於整個容器大小。它也適用於 RadioButton,但同一容器中別塞多個 CompoundButton,否則觸控派送會互相打架。

從基本用法一路談到列表複用、狀態加鎖、自造篩選器與觸控優化,CheckBox 雖小,學問卻不少。建議動手把範例跑一遍,感受會更深刻。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved