編輯:Android 資訊
0 和 1 是計算機的基石,在數理邏輯裡它們代表兩種狀態:真與假。看似簡單的 0 和 1,其實變化無窮。今天我就來聊聊 Android 控件裡這個帶著 0/1 魔力的傢伙——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 本身是一個展示給用戶看的視圖,所以我們應該用數據來驅動它的顯示。因此在 Activity 裡更推薦這樣寫:
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);這樣,當數據變化時,視圖狀態就會跟著變。注意,監聽器一定要在 setChecked 之前設置,這樣才能體現「數據控制視圖」的思路。
單獨用 Checkbox 很 easy,接下來才是複雜情況:Checkbox 如何跟 ListView/RecyclerView(以下簡稱 LV/RV)配合。這就不能只靠直覺了,因為 LV/RV 裡的視圖數量遠小於數據集的條目數——屏幕上的列表項是可以復用的。關於這點,初學者可以看看 The World Of ListView。正因復用機制,如果不用數據來控制 Checkbox 狀態,就會出現錯亂:你只勾選了第一個 Item,往下滑卻發現下面的 Item 也變成選中了。當年我剛學 Android 也踩過這坑,關鍵還是在於用數據控制顯示。因此在 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());這種方法基本正確,但得為每個數據項額外加一個字段來記狀態,代價有點大:既非必要,又會讓本地數據結構和服務端不一致。通常列表裡用 Checkbox,無非是把選中的 item 記下來——可以這樣理解:選中狀態是「列表」給的,item 本身應該是無狀態的。那怎麼重構?Android 為我們準備了一個完美的數據結構:SparseArray,或者更合適的 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();
若想取出所有選中項,有了 SparseBooleanArray 就好辦多了:
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 照樣觸發。怎麼辦?程序員遇到問題,通常先想最笨的辦法:既然 onCheckedChanged 還會觸發,那我在裡面把 buttonView 再設成 !isChecked 不就行了。
holder.cbx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { buttonView.setChecked(!isChecked); //... } });但這樣會再次調用 buttonView(也就是 holder.cbx)的 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; //... } });給 cbx 加鎖其實很常用。比如你在 onCheckedChanged 裡發了個請求,而請求結果又反過來要更新這個 cbx 的選中狀態,你就得用 lockState 直接改 cbx,才能保證它和 mCheckStates 一致。
還有一種情況:如果 onCheckedChanged 時 isChecked 和 mCheckStates.get(pos) 相同,會怎樣?
@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 } }這會讓你的 //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 和 SparseBooleanArray 聯用,並考慮到加鎖與過濾重選,那說明你用 Checkbox 的姿勢已經擺正了。但精彩的地方才剛開始。
一個只能上下滑的列表是最簡單的用法。由於列表項太多,產品通常會加篩選功能。做篩選大家常想到 Spinner,但系統自帶的 Spinner 擴展性太差、長得又醜,往往被棄用——我就是其中之一。經過一番琢磨,我找到了一種很優雅的機制來實現列表篩選,下面分享給大家。
先請出今天的另一位主角:PopupWindow。原理是這樣的:先給 Checkbox 設 setOnCheckedChangeListener,在 onCheckedChanged 的 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(); } }效果圖:

源碼
簡單解釋一下:重點在 PopupWindow 裡,MainActivity 的 Checkbox 作為參數傳了進去。用戶點擊 MainActivity 的 Checkbox,進入 isChecked 分支,PopupWindow 展示出來,操作環境就切換到了 PopupWindow。等用戶選好篩選條件,PopupWindow 把結果設給 outCbx 並改變其狀態,從而觸發 MainActivity 中 onCheckedChanged 的否定分支——此時展示一個 Toast(實際應用裡可以是網絡請求)。同時,由於 PopupWindow 的代碼並不阻塞操作,會接著執行 super.dismiss(),所以你不用在 MainActivity 裡操心它的關閉。最後 MainActivity 還加了 try-catch 以防萬一。這種機制把篩選操作從 Activity 中剝離了出來,以後寫篩選完全可以獨立於 Activity,是很軟件工程的做法。
好啦,精彩的部分講完,最後再上點私房菜。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); } } }這個類可以當 FrameLayout 用,把 CheckBox 放進去,它的點擊區域就變成整個 FrameLayout 了。它也適用於 RadioButton,但別在一個裡面放多個 CompoundButton(- -!)
ok,今天的詳解就到這兒,視反饋程度再更新博文和源碼!
Android 應用瘦身實戰:安裝包從 18MB 減到 12.5MB
開篇語 前陣子老大交給我一個任務:幫我們開發的直播應用做 Android 端的安裝包瘦身。我花了大約一週時間,把安裝包從 18MB 一路減到了 12.5MB。其實原本完全
Android Context 到底是什麼?一篇講透它的由來與數量
先把 Context 想成「場景」 一個 Context 對應一個場景,而場景就是使用者與軟體互動的一段過程。以微信為例,聊天頁、通訊錄、朋友圈,以及它們背後的資料,各自
Android SQLite 快速入門指南
SQLite 是 Android 開發中最常打交道的資料庫方案。作為一款輕量級資料庫,它的設計初衷就是「嵌入式」,如今已被大量裝置採用。它極度省資源,在嵌入式環境中往往只
Android 推送技術深入研究
前言 近來鑽研 Android 推送的實現原理,折騰了一天一夜,總算有些心得,寫下來既為分享,也為吐槽。需要提前說明的是,其中部分內容偏向底層硬件與通信領域,我對這些一竅