xml文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:weightSum="1"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="1"> <CheckBox android:id="@+id/checkbox1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="篮球" /> <CheckBox android:id="@+id/checkbox2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="足球" /> <CheckBox android:id="@+id/checkbox3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="乒乓球" /> <CheckBox android:id="@+id/checkbox4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="羽毛球" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_gravity="center_horizontal"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="获取选中的值"/> </LinearLayout> </LinearLayout>
Actity文件:
package com.example.lolli.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private CheckBox checkBox1, checkBox2, checkBox3, checkBox4; private Button button1; private List<CheckBox> checkBoxList = new ArrayList<CheckBox>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化控件 checkBox1 = (CheckBox) findViewById(R.id.checkbox1); checkBox2 = (CheckBox) findViewById(R.id.checkbox2); checkBox3 = (CheckBox) findViewById(R.id.checkbox3); checkBox4 = (CheckBox) findViewById(R.id.checkbox4); button1 = (Button) findViewById(R.id.button1); // 将所有的checkbox放到一个集合中 checkBoxList.add(checkBox1); checkBoxList.add(checkBox2); checkBoxList.add(checkBox3); checkBoxList.add(checkBox4); //给按钮设置点击事件 button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { StringBuffer sb = new StringBuffer(); //遍历集合中的checkBox,判断是否选择,获取选中的文本 for (CheckBox checkbox : checkBoxList) { if (checkbox.isChecked()){ sb.append(checkbox.getText().toString() + " "); } } if (sb!=null && "".equals(sb.toString())){ Toast.makeText(getApplicationContext(), "请至少选择一个", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(), sb.toString(), Toast.LENGTH_SHORT).show(); } } }); } }