当前位置: 代码迷 >> Android >> Android 之 复选框(CheckBox)的运用
  详细解决方案

Android 之 复选框(CheckBox)的运用

热度:364   发布时间:2016-05-01 13:47:42.0
Android 之 复选框(CheckBox)的使用
1.调用setOnCheckedChangeListener()方法,并把 CompoundButton.OnCheckedChangeListener实例作为参数传入
2.在CompoundButton.OnCheckedChangeListener的onCheckedChanged()方法里,取得被选中复选框的实例
  /** Called when the activity is first created. */	private CheckBox c1,c2 ;	private Button button;	    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        c1 = (CheckBox) findViewById(R.id.CheckBox01);        c2 = (CheckBox) findViewById(R.id.CheckBox02);        button = (Button) findViewById(R.id.Button01);                //注册事件监听        c1.setOnCheckedChangeListener(new CheckBoxListener());        c2.setOnCheckedChangeListener(new CheckBoxListener());        button.setOnClickListener(new ButtonClickListener());            }        //定义事件    class CheckBoxListener implements OnCheckedChangeListener{		@Override		public void onCheckedChanged(CompoundButton buttonView,				boolean isChecked) {			if(isChecked){				//Toast				Toast.makeText(CheckBoxActivity.this, buttonView.getText()+"被选择",Toast.LENGTH_SHORT ).show();			}else{				Toast.makeText(CheckBoxActivity.this, buttonView.getText()+"取消选择",Toast.LENGTH_SHORT ).show();			}		}    }        class ButtonClickListener implements OnClickListener{    	String buffer = "";		public void onClick(View v) {			if(c1.isChecked())				buffer = buffer+c1.getText();			if(c2.isChecked())				buffer = buffer +c2.getText();			Toast.makeText(CheckBoxActivity.this, buffer+"被选择", Toast.LENGTH_SHORT).show();		}    }


main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TextView      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="@string/hello"    />    <CheckBox android:text="金钱" android:id="@+id/CheckBox01" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox><CheckBox android:text="地位" android:id="@+id/CheckBox02" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox><Button android:id="@+id/Button01" android:text="确定" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button></LinearLayout>


运行效果

  相关解决方案