Android switch當代碼setCheck時,不呼叫onCheckedChanged
阿新 • • 發佈:2019-02-03
最近做專案需要使用switch控制元件去設定手勢密碼,當手動開啟或者關閉switch控制元件時,會跳轉到設定手勢密碼頁面,並且設定成功後,會儲存switch狀態到檔案中。每次進入手勢密碼頁面,都去獲取switch狀態,然後通過setChecked設定switch狀態。實際使用中發現當手動或者使用開啟關閉switch時,都會進入onCheckedChanged回撥方法。導致一直進入設定手勢密碼頁面。
最開始的解決方案是設定一個標誌位來進行控制,但實際調測過程中發現onCheckedChanged有時會被呼叫多次,導致不是每次操作都符合預期;之後找到另一種方案是onCheckedChanged中呼叫switch.isPressed方法,如果為true,則處理,否則當做程式處理。但當滑動開啟關閉switch時不起作用。該方案應該在Radiogroup和checkbox控制元件有作用(未測試過)。
最終找到的解決方案是在程式碼呼叫setchecked之前unregister listener,呼叫完之後register listener,最後成功解決該問題。部分程式碼如下:
@Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Intent toCreateGesturePwd = new Intent(this, CreateGesturePasswrodActivity.class); startActivity(toCreateGesturePwd); }
@Override protected void onResume() { super.onResume(); //反註冊 mGesturePwdSwitch.setOnCheckedChangeListener(null); if (isShowGesturePwd) { mGesturePwdSwitch.setChecked(true); } else { mGesturePwdSwitch.setChecked(false); } //註冊回撥 mGesturePwdSwitch.setOnCheckedChangeListener(this); }