android基本控件示例CheckBox(03)

//CheckBox示例:要本身建一個Activity
//根據佈局文件初始化
	private CheckBox hobby1;
	private CheckBox hobby2;
	private CheckBox hobby3;
	private CheckBox hobby4;
	private CheckBox checkAll;
                hobby1 = (CheckBox) this.findViewById(R.id.hobby1);
		hobby2 = (CheckBox) this.findViewById(R.id.hobby2);
		hobby3 = (CheckBox) this.findViewById(R.id.hobby3);
		hobby4 = (CheckBox) this.findViewById(R.id.hobby4);
		checkAll = (CheckBox) this.findViewById(R.id.checkAll);
//設置監聽事件,定義一個有名字的監聽類,之因此不用匿名內部類的形式,是由於有多個控件都要使用這個監聽
private OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
			if (arg0.isChecked()) {
				Toast.makeText(MainActivity.this, "您選擇了" + getResult(),
						Toast.LENGTH_SHORT).show();
			}
		}
	};
// 獲取多選項中的結果,利用isCheck()來判斷那個被勾選了
	public String getResult() {
		StringBuffer sb = new StringBuffer();
		if (this.hobby1.isChecked()) {
			sb.append(hobby1.getText());
		}
		if (this.hobby2.isChecked()) {
			sb.append(hobby2.getText());
		}
		if (this.hobby3.isChecked()) {
			sb.append(hobby3.getText());
		}
		if (this.hobby4.isChecked()) {
			sb.append(hobby4.getText());
		}
		return sb.toString();

	}
// 給全選按鈕設置單擊監聽事件,在佈局中已經定義了監聽,因此根據Id在這裏獲取監聽
	public void checkAll(View view) {
		switch (view.getId()) {
		case R.id.register:
			Toast.makeText(MainActivity.this, "您選擇了" + getResult(),
					Toast.LENGTH_SHORT).show();
			break;

		case R.id.checkAll:
			// 將全選按鈕的單擊狀態給其餘的複選框
			boolean boovalue = this.checkAll.isChecked();
			this.hobby1.setChecked(boovalue);
			hobby2.setChecked(boovalue);
			hobby3.setChecked(boovalue);
			hobby4.setChecked(boovalue);
			break;
		}
	}
//佈局文件
 <CheckBox
        android:id="@+id/hobby1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="打籃球" />
    <CheckBox
        android:id="@+id/hobby2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="游泳" />
    <CheckBox
        android:id="@+id/hobby3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跑步" />
     <CheckBox
        android:id="@+id/hobby4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="LOL" />
     <CheckBox
        android:id="@+id/checkAll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="全選/反選" 
        android:onClick="checkAll"/>
      <Button
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="提交" 
        android:onClick="checkAll"/>
相關文章
相關標籤/搜索