本帖最後由 tonyh 於 2017-8-12 16:37 編輯
CheckBox 元件支援多選多的選取操作。
- package com.example.student.myapplication;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.widget.CheckBox;
- import android.widget.CompoundButton;
- import android.widget.TextView;
- public class MainActivity extends AppCompatActivity {
- private TextView tv2;
- private CheckBox cb1,cb2,cb3,cb4,cb5;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- tv2= (TextView) findViewById(R.id.textView2);
- cb1= (CheckBox) findViewById(R.id.checkBox1);
- cb2= (CheckBox) findViewById(R.id.checkBox2);
- cb3= (CheckBox) findViewById(R.id.checkBox3);
- cb4= (CheckBox) findViewById(R.id.checkBox4);
- cb5= (CheckBox) findViewById(R.id.checkBox5);
- cb1.setOnCheckedChangeListener(myListener);
- cb2.setOnCheckedChangeListener(myListener);
- cb3.setOnCheckedChangeListener(myListener);
- cb4.setOnCheckedChangeListener(myListener);
- cb5.setOnCheckedChangeListener(myListener);
- }
- private CompoundButton.OnCheckedChangeListener myListener=new CompoundButton.OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- String str="";
- if(cb1.isChecked())
- str+=cb1.getText().toString()+" ";
- if(cb2.isChecked())
- str+=cb2.getText().toString()+" ";
- if(cb3.isChecked())
- str+=cb3.getText().toString()+" ";
- if(cb4.isChecked())
- str+=cb4.getText().toString()+" ";
- if(cb5.isChecked())
- str+=cb5.getText().toString()+" ";
- tv2.setText(str);
- }
- };
- }
複製代碼 |