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

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>();

	@Override
	public 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);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		String 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值