您的位置:首页 > 其它

安卓控件使用系列12:CheckBox复选框控件的使用

2015-10-02 15:42 357 查看
安卓中CheckBox控件是我们经常需要使用的控件之一,下面将使用方法分享给大家。

这里的例子实现的是四个选项,可以选择其中的一个或者多个,然后点击按钮,会显示选择的内容。

整体思路:首先在xml文件中定义一个Button控件,新建一个新的xml文件,在里面加入一个CheckBox控件;然后在活动中定义一个字符串数组,里面存放四个选项的内容,定义一个ChechBox的动态数组,找到原来xml文件的ID,遍历一遍字符串数组,并把其中的每一个字符串依次绑定到新的xml文件的CheckBox控件上,并加入到原来xml文件中;然后定义Button的OnClick事件,在里面遍历所有的CheckBox,如果被选中则显示选中的内容,如果没有选中就显示”没有选择“的信息(使用一个提示框提示用户)。

activity_main.xml文件:

<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="确定"
/>


checkbox.xml文件:

<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/checkbox"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >

</CheckBox>
MainActivity.java文件:

private List<CheckBox> checkBoxs=new ArrayList<CheckBox>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
//向已有的LinearLayout中动态添加控件
String[] checkboxText=new String[]{"喜欢旅游吗?","喜欢看娱乐新闻吗?","喜欢吃水果吗?","喜欢运动吗?"};
//动态加载布局
LinearLayout linearLayout=(LinearLayout)getLayoutInflater().inflate(R.layout.activity_main, null);
for(int i=0;i<checkboxText.length;i++){
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)findViewById(R.id.button);
button.setOnClickListener(this);
}

public void onClick(View arg0) {
// 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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: