【问题标题】:Inflate a linear layout from R.id and not R.layout从 R.id 而不是 R.layout 膨胀线性布局
【发布时间】:2013-03-08 13:29:34
【问题描述】:

我要疯了。我有一个片段的布局。在里面我有一个带有 id 的 LinearLayout,例如 myLinearLayout。基本上,我想做以下事情:

LinearLayout newLayout = new LinearLayout(this);
LinearLayout layoutCopy = inflatefrom(R.id.myLinearLayout);
newLayout.addView(layoutCopy);

我该怎么做?

【问题讨论】:

    标签: android android-linearlayout viewgroup inflate


    【解决方案1】:

    您不能从R.id 中扩充Layout,但您可以通过R.layout 扩充Layout 并使用返回的视图来检索您需要的R.id

    例如

    LayoutInflater inflater = LayoutInflater.from(this);
    View view = inflater.inflate(R.layout.mylayout, null);
    LinearLayout layoutCopy = (LinearLayout)view.findViewById(R.id.myLinearLayout);
    

    检查错别字

    【讨论】:

      【解决方案2】:

      试试这个:

      View.inflate(Context, R.id, ViewGroup)
      

      【讨论】:

        【解决方案3】:

        实际上是黑带,这就是我解决它的方法,但是在将复制的布局添加到新布局时仍然出现错误。原因是我要复制的布局仍然有父级。这是一个完整的解决方案(layoutRoot 是一个位于 res/layout 中的 xml 布局,而 myLinearLayout 是文件 layoutRoot 内的一个 LinearLayout。layoutToPlaceCopiedLayout 是我想要放置复制的布局的布局内的一个 LinearLayout)。

        LinearLayout newLayout = (LinearLayout)findViewById(R.id.layoutToPlaceCopiedLayout)
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layoutRootCopy = (LinearLayout)inflatefrom(R.layout.layoutRoot);
        LinearLayout layoutCopy = (LinearLayout)layoutRootCopy.findViewById(R.id.myLinearLayout);
        ViewGroup parent = (ViewGroup)layoutCopy.getParent();
        int index = parent.indexOfChild(layoutCopy);
        parent.removeView(layoutCopy);
        newLayout.addView(layoutCopy, index);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多