android.widget.Switch - オン/オフイベントリスナー? 質問する

android.widget.Switch - オン/オフイベントリスナー? 質問する

スイッチ ボタン android.widget.Switch (API v.14 から利用可能) を実装したいと思います。

<Switch
    android:id="@+id/switch1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Switch" />

しかし、ボタンのイベント リスナーを追加する方法がわかりません。「onClick」リスナーにする必要がありますか? また、それが「オン」になっているかどうかはどうすればわかりますか?

ベストアンサー1

スイッチはCompoundButtonの属性を継承するので、オンチェック変更リスナー

mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // do something, the isChecked will be
        // true if the switch is in the On position
    }
});

おすすめ記事