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();
}
}
总结:只要是用按钮什么的改变一个数值,那么就是利用监听去做的。