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

但没有一个运行良好。


当前回答

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

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

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

其他回答

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

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

您膨胀一个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);

希望这个方法对你有用。

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

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

布局的通货膨胀

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