问题
I am trying to add multiple relative layouts to a Linear layout. I am using the following lines of code.
LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout item = (LinearLayout)findViewById(R.id.reviews);
for(int i=0 ; i<2 ; i++){
View child = inflator.inflate(R.layout.review_item, null);
child.setId(i);
child.setTag(i);
item.addView(child);
}
But I can only see one child view. Can anyone tell me where I am going wrong.
回答1:
Declare the LinearLayout item
outside of the for loop.
The way you're doing it the variables value will be overwritten each time you run through the for loop. So your method should look like this:
public void somemethod(){
LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout item = (LinearLayout)findViewById(R.id.reviews);
for(int i=0 ; i<2 ; i++)
{
View child = inflator.inflate(R.layout.review_item, null);
child.setId(i);
child.setTag(i);
item.addView(child);
}
}
回答2:
You need to take the first two lines outside of the for loop. You're inflating the LinearLayout twice, which overrides the first layout you inflate, rather than adding to it. By putting those two lines before the for loop starts, you'll add both child views to a single LinearLayout.
来源:https://stackoverflow.com/questions/30545889/not-being-able-to-add-multiple-child-views-to-parent-view