您的位置:首页 > 其它

利用XML布局文件动态创建CheckBox

2011-06-19 19:42 288 查看
要动态创建CheckBox,一个比较好的考虑是:

单纯考虑设置组件的属性,XML布局文件无疑是最简单的方法。可以在XML布局文件中先配置一个或若干CheckBox,然后以这些配置为模板来动态创建CheckBox对象

这里先 定义一个String 数组,数组元素表示CheckBox的文本,然后根据String数组的元素个数来创建CheckBox对象

步骤如下:

1. 使用getLayoutInflater().inflate()方法来装载main.xml布局文件,并返回一个LinearLayout对象(linearLayout).

2. 使用getLayoutInflater().inflate()方法来装载checkbox.xml布局文件,并返回一个LinearLayout对象(checkboxLinearLayout).

3. 调用checkboxLinearLayout.findViewById()方法来获得CheckBox对象,并根据String数组中的值设置CheckBox的文本。

4. 调用linearLayout.addView()方法将checkboxLinearLayout添加到linearLayout中。

5. 根据String数组的元素重复第2,3,4 步,直到处理完String数组中的最后一个元素为止.

实现效果如图所示:



在onCreate()动态创建CheckBox对象的代码如下:

public void onCreate(Bundle bundle)  {
    super.onCreate(bundle);
    String[]  checkboxText = new String[]{"Android","iPhone","Windows Mobile","Symbian","Meego","BlackBeery","Palm"};
    //装载main.xml文件
   LinearLayout  linearLayout  = (LinearLayout)getLayoutInflater().inflate(R.layout.main,null);
   for(int i=0;i<checkboxText.length;i++)   {
       //装载checkbox.xml文件
       LinearLayout  checkboxLinearLayout =  (LinearLayout) getLayoutInflater().inflate(R.layout.checkbox,null);
       //获得checkbox.xml文件中的CheckBox对象
       checkboxs.add((CheckBox)checkboxLinearLayout.findViewById(R.id.checkbox));
       checkboxs.get(i).setText(checkboxText[i]);      //设置CheckBox的文本
       //将包含  CheckBox  的LinearLayout 对象添加到由主布局文件生成的LinearLayout 对象中
       linearLayout.addView(checkboxLinearLayout,i); 
   }
   setContentView(linearLayout);
   Button button = (Button) findViewById(R.id.button);
   button.setOnClickListener(this);
}


具体代码见 ch05_dynamiccheckbox工程
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐