【问题标题】:android how to inflate one view defined in a layout file (not whole file)android如何膨胀布局文件中定义的一个视图(不是整个文件)
【发布时间】:2019-07-15 16:50:11
【问题描述】:

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

<anyLayout ...>

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

    <!-- many many more -->

</anyLayout>

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

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

【问题讨论】:

    标签: android android-layout android-inflate


    【解决方案1】:

    他们可以放入一个布局文件并单独充气吗?

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

    会根据不同的条件创建(膨胀)不同的视图组件(例如 Button、TextView)。

    听起来你可以通过使用ViewStub tags来实现你想要的。

    为此,您可以照常创建主布局文件。但是,在您想要拥有动态内容的任何地方,您都可以添加&lt;ViewStub&gt; 标记。然后,在 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();
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多