我想将以下元素结构动态添加到布局。
我得到一个项目列表,对于每个项目,我必须将一些元素插入主线性布局(linearLayout2)。
我在下面尝试了一些代码,但它没有显示布局。 如果我将TextView直接添加到父布局中,它是可见的,但是如果我想遵循下面的xml结构,屏幕上不会添加任何内容。
我要添加的布局:
<RelativeLayout>
<TextView android:id="@+id/textView1" />
<CheckBox />
<TextView android:id="@+id/textView2" />
<TextView android:id="@+id/textView3" />
<TextView android:id="@+id/textView4" />
</RelativeLayout>
AsyncTask OnResponse():
LinearLayout linearLayout = (LinearLayout) currentActivity.findViewById(R.id.linearLayout2);
for(int i = 0; i < homeworkList.size(); i++){
RelativeLayout layout = new RelativeLayout(currentActivity,null, R.style.HomeworkLayout);
TextView text = new TextView(currentContext);
text.setTextAppearance(currentContext,R.style.HomeworkTile);
layout.addView(text);
linearLayout.addView(layout);
}
这是将动态添加到页面中的好方法吗?
为什么添加相对布局不起作用?
答案 0 :(得分:0)
如果你想构建那种布局,你需要使用这个代码(你需要将相对布局添加到线性布局,然后你可以将文本视图放在相对布局中)
LinearLayout linearLayout = (LinearLayout)currentActivity.findViewById(R.id.linearLayout2);
//Add RelativeLayout to LinearLayout
RelativeLayout layout = new RelativeLayout(currentActivity,null, R.style.HomeworkLayout);
linearLayout.addView(layout);
for(int i = 0; i < homeworkList.size();
{
//Add TextViews to RelativeLayout
TextView text = new TextView(currentContext);
text.setTextAppearance(currentContext,R.style.HomeworkTile);
//Make sure the TextView got a width and a height
TableRow.LayoutParams paramsExample = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,1.0f);
text.setLayoutParams(paramsExample);
layout.addView(layout);
}
答案 1 :(得分:0)
我使用布局inflaters从java加载动态视图
View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,linearLayout,false)
linearLayout.addView(view);
如果您想访问子视图
TextView tv = (TextView)view.findViewById(R.id.textView_Id);
http://www.mysamplecode.com/2011/10/android-dynamic-layout-using-xml-add.html
答案 2 :(得分:0)
linearLayout.addView(text);
linearLayout.addView(layout);
您要将TextView
和RelativeLayout
添加到LinearLayout
。
您需要将TextView
添加到RelativeLayout
,而不是为每个循环创建新的RelativeLayout
:
RelativeLayout layout = new RelativeLayout(currentActivity,null, R.style.HomeworkLayout);
for(int i = 0; i < homeworkList.size(); i++){
TextView text = new TextView(currentContext);
text.setTextAppearance(currentContext,R.style.HomeworkTile);
layout.addView(text);
}
linearLayout.addView(layout);