我有一个用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(...)

但没有一个运行良好。


当前回答

如果你不在一个活动中,你可以使用静态的from()方法从LayoutInflater类获得一个LayoutInflater,或者从上下文方法getSystemService()请求服务:

LayoutInflater i;
Context x;       //Assuming here that x is a valid context, not null

i = (LayoutInflater) x.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//OR
i = LayoutInflater.from(x);

(我知道这已经是4年前的事了,但仍然值得一提)

其他回答

布局的通货膨胀

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

attachtorroot设置为True

假设我们在XML布局文件中指定了一个按钮,将其布局宽度和布局高度设置为match_parent。

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/custom_button">
</Button>

在此按钮上单击事件,我们可以设置以下代码来膨胀此活动的布局。

LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(R.layout.yourlayoutname, this);

希望这个方法对你有用。

更简单的方法是使用

View child = View.inflate(context, R.layout.child, null)
item.addChild(child) //attach to your item

使用Kotlin,您可以使用:

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

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