问如何动态加载xml模板,并且实例化多个对象,就是id不一样怎么办?

logohoo 2015-06-24 04:18:54
模板保存文件为R.layout.item_view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="left|center"
android:layout_weight="1" >
<CheckBox
android:id="@+id/checkbox_select"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</LinearLayout>


如下面xml模板,现在我想实例化多个xml布局和对象,但是android:id="@+id/checkbox_select"这个id要不同个怎么办啊?
如这样:LinearLayout layout_item = (LinearLayout)this.inflate(context, R.layout.item_view, null);就能实例化一个,然后this.add它就OK了。
但是我要实例化多个这样的布局,怎么弄啊?
如:LinearLayout layout_item1 = (LinearLayout)this.inflate(context, R.layout.item_view, null);
LinearLayout layout_item2 = (LinearLayout)this.inflate(context, R.layout.item_view, null);
LinearLayout layout_item3 = (LinearLayout)this.inflate(context, R.layout.item_view, null);
....
像上面实例化三个对象后,android:id="@+id/checkbox_select"都是相同的,就直接layout_item1.RelativeLayout.checkbox_select吗?
还想问,layout_item1对象实例化后,如何对checkbox_select进行访问?
...全文
123 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Utopia 2015-06-24
  • 打赏
  • 举报
回复
CheckBox checkBox = layout_item1.findViewById(R.id.checkbox_select);
logohoo 2015-06-24
  • 打赏
  • 举报
回复
谢谢Arnold9009,这个搞定了, 那么问: LinearLayout layout_item1 = (LinearLayout)this.inflate(context, R.layout.item_view, null); layout_item1对象实例化后,如何对checkbox_select进行访问?
Arnold9009 2015-06-24
  • 打赏
  • 举报
回复
xml里可以先不指定id,在代码中动态生成的时候,再调用setId方法设置一个 id可以在value中预定义一些

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧