利用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对象的代码如下:
具体代码见 ch05_dynamiccheckbox工程
单纯考虑设置组件的属性,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工程
相关文章推荐
- Hibernate动态建表,通过hbm.xml配置文件创建数据表,进行数据库操作, 动态模型
- Android中不使用布局文件,java代码动态创建布局及控件
- Androiid 如何动态加载assets目录下的xml布局文件(包括Drawable xml)
- Android学习笔记_31_通过后台代码生成View对象以及动态加载XML布局文件到LinearLayout
- Android学习笔记_31_通过后台代码生成View对象以及动态加载XML布局文件到LinearLayout
- 利用virsh和xml文件创建虚拟机
- 从assets中读取xml文件再动态的创建界面
- 利用MyEclipse创建hibernate视图的hbm.xml文件及其手动设置事项
- ViewPager中动态添加XML布局文件,并获取XML文件中控件ID的操作(inflate)
- 如何使用PHP DOM创建动态的XML文件
- 关于Fragment的学习笔记1——利用布局文件创建固定Fragment
- 如何使用PHP DOM创建动态的XML文件
- 利用Hibernate工具,通过xml文件自动创建表
- android学习之布局(如何动态加入其它xml文件中的控件)
- 动态创建表格js文件,javascript,Ajax,DHTML动态实现表格的创建,动态读取XML中的文件,读取dom节点的例子。
- java中利用spring动态的创建hibernate的配置文件
- 关于 Eclipse 创建 Dynamic Web Project (动态的 WEB 项目) 为什么会出现没有web.xml配置文件的问题
- Eclipse中Web项目创建完成后,动态添加web.xml文件。
- Android开发之动态创建布局文件及控件
- 关于 Eclipse 创建 Dynamic Web Project (动态的 WEB 项目) 为什么会出现没有web.xml配置文件的问题