Android 之 复选框(CheckBox)的使用
16lz
2021-01-23
1.调用setOnCheckedChangeListener()方法,并把 CompoundButton.OnCheckedChangeListener实例作为参数传入
2.在CompoundButton.OnCheckedChangeListener的onCheckedChanged()方法里,取得被选中复选框的实例
main.xml
运行效果
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{@Overridepublic void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {if(isChecked){//ToastToast.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>
运行效果
更多相关文章
- Android利用资源名称获取其id之getIdentifier()方法
- asynchttpclient的post方法发送json格式参数和表单格式参数
- Android中button的onClick事件几种方法
- Android 关闭多个Activity的实现方法
- Android中几种延后处理事件的方法
- Android判断包名和类名是否存在的方法
- Android SDK 1.5 "--core-library" build error问题解决方法
- android http通信(二) 英译汉字典实例探究网络通信三种方法