通过从不同的 XML 文件中进行选择以编程方式完成布局

Complete layout programmatically by choosing from different XML files

我有两个布局几乎相同的活动。只有底部的按钮不同。

The empty space at the top is an empty EditText that is supposed to show the amount of the expense and is filled in at runtime. Same goes for the empty TextView for the date.

我知道可以将按钮从 XML 文件中删除并以编程方式填充它们。但我喜欢轻松更改 XML 文件。

因此我的问题是:是否可以在运行时从另外两个 XML 文件中进行选择以添加按钮?
我想 "placeholder views" 存在,可以用选定的 XML 布局来膨胀。

您可以在 xml 文件中创建三个按钮。不想显示的可以隐藏。

A ViewStub 很适合这种情况。您可以指定应该在运行时膨胀的 XML,然后膨胀它。

ViewStub vs = (ViewStub) findViewById(R.id.my_viewstub);
vs.setLayoutResource(R.layout.my_layout);
vs.inflate();