checkbox复选框的使用(提示所有复选框已经选中的内容)

来源:互联网 发布:腾讯软件管家mac版 编辑:程序博客网 时间:2024/05/10 21:09

1.直接在layout下面创建一个xml文件:checkbox.xml

<?xml version="1.0" encoding="utf-8"?><CheckBox xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent" android:id="@+id/checkbox"android:layout_height="wrap_content"></CheckBox>


1.1父布局文件:

<?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"><Button android:id="@+id/button" android:layout_width="fill_parent"android:layout_height="wrap_content" android:text="确定" /></LinearLayout>



2.写代码:

使用一种动态加载布局的方式去加载布局的方法。用的inflate就是了。

getlayoutinflater 返回一种动态加载的布局:利用xml加载。(说白了就是直接加载一个动态的布局文件)

建立一个checkbox的数组,然后用一个字符串的数组一个个给这个checkbox进行赋值就好了。

然后就可以给一个linear布局添加需要的组件。

最后用在一个监听里用遍历获得checkbox的选项。

用对话框将需要的进行展示就好了。


package com.example.marvinedittext2;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.app.AlertDialog;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.CheckBox;import android.widget.LinearLayout;public class Main extends Activity implements OnClickListener {/** Called when the activity is first created. */private List<CheckBox> checkBoxs = new ArrayList<CheckBox>();@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// setContentView(R.layout.main);String[] checkboxText = new String[] { "您是学生吗?", "是否喜欢android?","您喜欢旅游吗?", "打算出国吗?" };// 动态加载布局LinearLayout linearLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.main, null);// 给指定的checkbox赋值for (int i = 0; i < checkboxText.length; i++) {// 先获得checkbox.xml的对象CheckBox checkBox = (CheckBox) getLayoutInflater().inflate(R.layout.checkbox, null);checkBoxs.add(checkBox);checkBoxs.get(i).setText(checkboxText[i]);// 实现了在linearLayout.addView(checkBox, i);}setContentView(linearLayout);Button button = (Button) this.findViewById(R.id.button);button.setOnClickListener(this);}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubString s = "";for (CheckBox checkBox : checkBoxs) {if (checkBox.isChecked()) {s += checkBox.getText() + "\n";}}if ("".equals(s)) {s = "您还没有选中选项!!";}// 使用一个提示框来提示用户的信息new AlertDialog.Builder(this).setMessage(s).setPositiveButton("关闭", null).show();}}


总结:只要是用按钮什么的改变一个数值,那么就是利用监听去做的。





0 0
原创粉丝点击