activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Switch
android:id="@+id/sw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<android.support.v7.widget.SwitchCompat
android:id="@+id/swc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
やっちゃいがちな書き方
SomeActivity.java
switch.setOnClickListener(new OnClickListener() {
void onClick(View view) {
if (((Switch) view).isChecked()) {
// ...
} else {
// ...
}
}
});
OnClickListenerの呼び出し有無とUIの状態の関係
操作 | OnClickListener | Viewの状態(checked/unchecked) |
---|---|---|
クリック | 呼ばれる(当然) | 変わる |
フリック(左右にシュッとやるやつ) | 呼ばれない | 変わる |
結論
Switch
のchecked/unchecked状態をView.OnClickListener
でハンドリングしていると、
ユーザがフリックでスイッチ切り替えを行った場合に不整合が発生します。
なのでSwitch
を使う時はCompoundButton.OnCheckedChangeListener
を使うほうがよいとおもいます。
私見
OnCheckedChangeListener登録した状態でsetChecked呼ぶと(呼ばれてほしくない)コールバック呼ばれちゃうじゃん
↓
よしOnClickListener使おう
このパターンでやらかすことが多い気がする