LoginSignup
8
5

More than 5 years have passed since last update.

Switch, SwitchCompatでOnClickListenerを使わないほうが良い理由

Last updated at Posted at 2015-04-29
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使おう

このパターンでやらかすことが多い気がする

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5