【问题标题】:Not being able to add multiple child views to parent view无法将多个子视图添加到父视图
【发布时间】:2015-05-30 11:59:58
【问题描述】:

我正在尝试将多个相对布局添加到线性布局。我正在使用以下代码行。

        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);
        }

但我只能看到一个子视图。谁能告诉我哪里出错了。

【问题讨论】:

  • 你的线性布局的方向是什么??
  • 只引用你的线性父布局一次,把它放在for循环之外,也可以充气。
  • @DJphy 方向是水平的。我把它做成垂直的,它起作用了。谢谢你。你能把它作为答案发布吗?
  • 不需要它正常工作就足够了,也可以按照我在下面的帖子中所做的评论/答案。应该这样做,快乐的编码......
  • @DJphy 我确实关注了评论并再次感谢您:)

标签: android android-linearlayout android-relativelayout layout-inflater


【解决方案1】:

在 for 循环之外声明 LinearLayout item。 每次运行 for 循环时,变量值都会被覆盖。所以你的方法应该是这样的:

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】:

    您需要将前两行放在 for 循环之外。您将 LinearLayout 膨胀两次,这会覆盖您膨胀的第一个布局,而不是添加到其中。通过将这两行放在 for 循环开始之前,您可以将两个子视图添加到单个 LinearLayout。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      • 2013-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多