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.     } 

 

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