我有一个用XML定义的布局。它还包括:

<RelativeLayout
    android:id="@+id/item"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>

我想用其他XML布局文件来膨胀这个RelativeView。我可能会根据情况使用不同的布局。我该怎么做呢?我尝试了不同的变化

RelativeLayout item = (RelativeLayout) findViewById(R.id.item);
item.inflate(...)

但没有一个运行良好。


当前回答

我不确定我是否跟上了你的问题-你是否试图将子视图附加到RelativeLayout?如果是这样,你想做的事情如下:

RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
item.addView(child);

其他回答

使用Kotlin,您可以使用:

val content = LayoutInflater.from(context).inflate(R.layout.[custom_layout_name], null)

[your_main_layout].apply {
    //..
    addView(content)
}

布局的通货膨胀

View view = null;
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
view = inflater.inflate(R.layout.mylayout, null);
main.addView(view);

您膨胀一个XML资源。参见LayoutInflater文档。

如果你的布局是在mylayout.xml中,你会像这样做:

View view; 
LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
view = inflater.inflate(R.layout.mylayout, null);

RelativeLayout item = (RelativeLayout) view.findViewById(R.id.item);

我不确定我是否跟上了你的问题-你是否试图将子视图附加到RelativeLayout?如果是这样,你想做的事情如下:

RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
item.addView(child);

我使用了下面的代码片段,它为我工作。

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
linearLayout.addView(child);