android 如何膨胀布局文件(不是整个文件)中定义的一个视图

android how to inflate one view defined in a layout file (not whole file)

android 如何膨胀布局文件(不是整个文件)中定义的一个视图?例如,

<anyLayout ...>

    <Button ... />
    <TextView ... />

    <!-- many many more -->

</anyLayout>

将根据不同的条件创建(膨胀)不同的视图组件(例如 Button、TextView)。有没有办法在布局文件中膨胀一个组件而不是整个文件?

每个组件都可以在自己的布局文件中定义。有许多。他们可以放在一个布局文件中并单独充气吗?

Can they put into one layout file and inflated separately?

没有。当您扩充布局资源时,您就是在扩充该文件中的所有内容。

Different view components(e.g. Button, TextView) will be created (inflated) depending on different conditions.

听起来您可以使用 ViewStub tags 来实现您想要的效果。

为此,您需要照常创建主布局文件。但是,在任何您想要拥有动态内容的地方,您都可以添加一个 <ViewStub> 标签。然后,在 Java/Kotlin 中,在主布局膨胀后,您可以将不同的视图膨胀到 ViewStub 中。

  • main_layout.xml
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Header"/>

    <ViewStub
        android:id="@+id/stub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Footer"/>

</LinearLayout>
  • button.xml
<Button
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="CLICK ME">
  • text.xml
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Can't click me">
  • MainActivity.java
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);

    ViewStub stub = findViewById(R.id.stub);

    if (isUseButton) {
        stub.setLayoutResource(R.layout.button);
    } else {
        stub.setLayoutResource(R.layout.text);
    }

    stub.inflate();
}