1. 程式人生 > >CheckBox複選框的

CheckBox複選框的

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="你最大的夢想是:"
android:textColor="#000"
android:textSize="20dp" />

<CheckBox
    android:id="@+id/cb_5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:text="暴富"
    android:button="@drawable/bg_checkbox"
    android:textSize="20sp" />

<CheckBox
    android:id="@+id/cb_6"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:text="暴瘦"
    android:button="@drawable/bg_checkbox"
    android:textSize="20sp" />

<CheckBox
    android:id="@+id/cb_7"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:text="長高"
    android:button="@drawable/bg_checkbox"
    android:textSize="20sp" />

<CheckBox
    android:id="@+id/cb_8"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:text="變白"
    android:button="@drawable/bg_checkbox"
    android:textSize="20sp" />

在java檔案中 編寫如下

先宣告控制元件
mCb5=(CheckBox)findViewById(R.id.cb_5);
mCb6=(CheckBox)findViewById(R.id.cb_6);
mCb7=(CheckBox)findViewById(R.id.cb_7);
mCb8=(CheckBox)findViewById(R.id.cb_8);

mCb5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override//設定狀態發生變化的監聽事件
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        Toast.makeText(CheckBoxActivity.this,b?"哈哈有錢了":"想多了",Toast.LENGTH_SHORT).show();
    }
});
mCb6.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override//設定狀態發生變化的監聽事件
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        Toast.makeText(CheckBoxActivity.this,b?"你又瘦了":"別吃了胖死得了",Toast.LENGTH_SHORT).show();
    }
});
mCb7.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override//設定狀態發生變化的監聽事件
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        Toast.makeText(CheckBoxActivity.this,b?"看我一米八的大長腿":"呵呵,小矮子",Toast.LENGTH_SHORT).show();
    }
});
mCb8.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override//設定狀態發生變化的監聽事件
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        Toast.makeText(CheckBoxActivity.this,b?"一白遮白醜":"怕是白痴吧",Toast.LENGTH_SHORT).show();
    }
});

在這裡插入圖片描述