刺身タンポポ職人なう

文系女子大生がエンジニアとして就職してその後

Androidでトグルスイッチ(Switch)ボタンを作成してイベントを取得する

トグルスイッチを作ってみる

Androidでトグルスイッチを作成し、CompoundButton をつかってイベントを取得してみる。

f:id:tooooomin:20170320221547p:plain

レイアウト作成

<Switch android:id="@+id/toggle_switch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:textColor="#3e3e3e"
    android:text="toggle switch button"/>

CompoundButton を利用してイベントを取得

CompoundButtonpublic abstract class CompoundButton extends Button implements Checkable ってドキュメントに書いてあった。

CompoundButton | Android Developers

CheckBox, RadioButton, Switch, SwitchCompat, ToggleButton とかのイベントは CompoundButton で取得できるらしい。

OFF/ON のステートを持ったボタンの共通機能を具備した抽象クラスです。抽象クラスなのでこれ自体をそのまま部品として使うことはできません。

ボタンをチューンしよう! このサイト様に書いてあった。ありがとうございます。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    CompoundButton toggle = (CompoundButton) findViewById(R.id.toggle_switch);
    toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                Log.d("MainActivity", "ON");
            } else {
                Log.d("MainActivity", "OFF");
            }
        }
    });
}

ログ

03-20 09:12:09.969 4390-4390/com.example.hoge.aswitch D/MainActivity: OFF
03-20 09:12:11.055 4390-4390/com.example.hoge.aswitch D/MainActivity: ON
03-20 09:12:15.639 4390-4390/com.example.hoge.aswitch D/MainActivity: OFF
03-20 09:12:16.413 4390-4390/com.example.hoge.aswitch D/MainActivity: ON

参考

techbooster.jpn.org

qiita.com