您的位置:首页 > 其它

CheckBox的一些用法(内容包含动态加载布局)

2015-08-10 19:46 141 查看
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >

   <Button 

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:id="@+id/button"

       android:text="选择"/>
</LinearLayout>

//checkbox的xml文件

<?xml version="1.0" encoding="utf-8"?>

<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/cb"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content" >

</CheckBox>

public class CheckboxsActivity extends Activity implements OnClickListener {
private List<CheckBox> checkBoxs = new ArrayList<CheckBox>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 动态加载布局
LinearLayout linearlayout = (LinearLayout) getLayoutInflater().inflate(R.layout.main, null);
String[] ss = new String[]
4000
{ "你好吗?", "你喜欢android吗?", "你要去哪?", "还有呢?" };
// 动态加载checkbox并给赋值
for (int i = 0; i < ss.length; i++) {
CheckBox checkbox = (CheckBox) getLayoutInflater().inflate(R.layout.checkbox, null);
checkBoxs.add(checkbox);
checkBoxs.get(i).setText(ss[i]);
// 把checkbox添加到linearlayout中
linearlayout.addView(checkbox, i);
}
setContentView(linearlayout);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
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();
}

}



@1.有个小问题是如果AlertDialog在for循环代码中去了会出现弹出窗口要关闭很多次才能关,也就是说循环了几次就要关几次。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: