AndroidのCompoundButtonの操作

AndroidのCompoundButtonは、Buttonクラスを継承し、Checkableインターフェースを実装した抽象クラスです。CompoundButtonは、CheckboxやSwitchのように複数の状態を持つボタンと見なすことができます。

CompoundButtonの一般的なサブクラスには、Checkbox、RadioButton、Switchがあります。

CompoundButtonを使用する手順は次の通りです。

  1. XMLレイアウトファイルでCompoundButtonコントロールを定義することができます。例えば、Checkbox、RadioButton、またはSwitchです。
<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Checkbox" />

<RadioButton
    android:id="@+id/radiobutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="RadioButton" />

<Switch
    android:id="@+id/switch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
  1. Javaのコード内で、これらのCompoundButtonコントロールを見つけて、適切なリスナーを設定してください。
CheckBox checkbox = findViewById(R.id.checkbox);
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // 处理Checkbox的选中状态改变事件
    }
});

RadioButton radiobutton = findViewById(R.id.radiobutton);
radiobutton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // 处理RadioButton的选中状态改变事件
    }
});

Switch switchButton = findViewById(R.id.switch);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // 处理Switch的选中状态改变事件
    }
});

リスナーのコールバックメソッドでは、isCheckedパラメータを使用してCompoundButtonの選択状態を判断することができます。

bannerAds