Android學習(二)CheckBox 實現

實現步驟:

1.implements OnCheckedChangListener

2.實例化CheckBox對象

3.對象綁定setOnCheckdChangeListener監聽

4.重寫監聽函數onCheckedChanged(CompoundButton buttonView, boolean isChecked)

buttonView 選中狀態發生改變的那個按鈕
isChecked 表示按鈕新的狀態(true/false)

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
  1. package com.luwenjie.CheckBox; 
  2.  
  3. import android.app.Activity; 
  4. import android.os.Bundle; 
  5. import android.widget.CheckBox; 
  6. import android.widget.CompoundButton; 
  7. import android.widget.Toast; 
  8. import android.widget.CompoundButton.OnCheckedChangeListener; 
  9.  
  10. //使用狀態改變檢查監聽器 
  11. public class CheckBoxProjectActivity extends Activity implements OnCheckedChangeListener { 
  12.     private CheckBox cb1, cb2, cb3;//創建3個CheckBox對象 
  13.  
  14.     @Override 
  15.     public void onCreate(Bundle savedInstanceState) { 
  16.         super.onCreate(savedInstanceState); 
  17.         setContentView(R.layout.main); 
  18.         //實例化3個CheckBox 
  19.         cb1 = (CheckBox) findViewById(R.id.cb1); 
  20.         cb2 = (CheckBox) findViewById(R.id.cb2); 
  21.         cb3 = (CheckBox) findViewById(R.id.cb3); 
  22.          
  23.         cb1.setOnCheckedChangeListener(this); 
  24.         cb2.setOnCheckedChangeListener(this); 
  25.         cb3.setOnCheckedChangeListener(this); 
  26.     } 
  27.  
  28.     //重寫監聽器的抽象函數 
  29.     @Override 
  30.     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
  31.         //buttonView 選中狀態發生改變的那個按鈕 
  32.         //isChecked 表示按鈕新的狀態(true/false) 
  33.         if (cb1 == buttonView || cb2 == buttonView || cb3 == buttonView) { 
  34.             if (isChecked) { 
  35.                 //顯示一個提示信息 
  36.                 toastDisplay(buttonView.getText() + "選中"); 
  37.  
  38.             } else { 
  39.                 toastDisplay(buttonView.getText() + "取消選中"); 
  40.             } 
  41.         } 
  42.     } 
  43.     public void toastDisplay(String str) { 
  44.         Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); 
  45.     } 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章