我有一个用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年前的事了,但仍然值得一提)

其他回答

虽然回答晚了, 但是我想补充一种得到这个的方法

LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = layoutInflater.inflate(R.layout.mylayout, item );

Where item是要在其中添加子布局的父布局。

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

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

如果你试图将子视图附加到RelativeLayout?你可以照着做

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

如果你不在一个活动中,你可以使用静态的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年前的事了,但仍然值得一提)

这是很有帮助的,尽管这是一篇旧文章,如果从xml中被膨胀的子视图要被添加到视图组布局中,你需要调用inflation,并提示它将被添加到哪种类型的视图组中。如:

View child = getLayoutInflater().inflate(R.layout.child, item, false);

膨胀方法是非常重载的,并在文档中描述了这部分用法。我有一个问题,从xml膨胀的单一视图没有正确对齐在父,直到我做了这种类型的改变。