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

但没有一个运行良好。


当前回答

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

希望这个方法对你有用。

其他回答

使用Kotlin,您可以使用:

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

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

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

当在Kotlin中添加一个布局到一个Activity时,请参见以下步骤:

只添加在活动-一个布局作为父 new的Xml文件 给出R的值。 val parent: LinearLayout =findViewById(R.id.stars) Val view = LayoutInflater.from (applicationContext) .inflate (R.layout.another,家长,假)

如果父项不需要,可以为空,但是会出现警告信息

view.findViewById<ImageView>(R.id.ivTimer).setImageResource(R.drawable.t2)

任何视图都必须以这种方式设置值,最后添加

parent.apply {  addView(view)}

试试下面的代码:

如果你只是想扩大你的布局:

View View = LayoutInflater.from(context). inflation (r.b ayout.your_xml_layout,null);//扩展xml布局的代码 RelativeLayout item = view.findViewById(R.id.item);

如果你想在容器中膨胀布局(父布局):

LinearLayout父= findViewById(R.id.container);/ /父布局。 View View = LayoutInflater.from(context). inflation (r.b ayout.your_xml_layout,parent,false); RelativeLayout item = view.findViewById(R.id.item);//初始化布局&通过这个你也可以执行任何事件。 parent.addView(查看);//在父布局中添加膨胀布局。

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

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