0

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

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

我怎样才能做到这一点?

4

3 回答 3

1

试试这个:

View.inflate(Context, R.id, ViewGroup)
于 2013-11-11T21:29:59.010 回答
1

您不能Layout从其膨胀 a R.id,但您可以Layout通过膨胀R.layout并使用返回的视图来检索R.id您需要的。

例如

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

检查错字

于 2013-03-08T13:34:25.480 回答
0

实际上是黑带,这就是我解决它的方法,但是在将复制的布局添加到新布局时仍然出现错误。原因是我要复制的布局仍然有父级。这是一个完整的解决方案(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);
于 2013-03-09T07:07:35.307 回答