Not being able to add multiple child views to parent view

 ̄綄美尐妖づ 提交于 2019-12-25 14:19:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!