【问题标题】:ViewBinding - How to switch/choose layout dynamically (<include>)?ViewBinding - 如何动态切换/选择布局(<include>)?
【发布时间】:2020-11-15 16:56:48
【问题描述】:

我计划为配置文件片段提供两种布局版本,一种用于新用户,另一种用于登录用户。

如何在 Fragment 的 onCreateView() 方法中动态切换/选择必要的布局?

想到的最直接的想法是使用两个&lt;include&gt; 布局并根据变量将其中一个隐藏在onCreateView() 中。但我想知道是否有更聪明的方法。


当前布局 xml:
主要内容在第二个FrameLayout里面,我想有两个版本可供选择。

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.MainActivity">

    <ImageView
        android:id="@+id/profile_monk_head_imageview"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:contentDescription="@string/profile_monk_image_content_desc"
        android:src="@drawable/monk_head" />

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- This is what I want to switch out -->
        <FrameLayout ... >

    </androidx.core.widget.NestedScrollView>

</FrameLayout>

【问题讨论】:

    标签: android android-viewbinding


    【解决方案1】:

    如果 layoutId 事先未知(也称为动态绑定),则使用 DataBindingUtil 版本 inflate。否则,使用生成的 Binding 的 inflate 方法来确保类型安全的膨胀。

    Crosslink reference

    【讨论】:

    • 这是创建fragment的主布局吧?但是如何使用生成的绑定对象在布局 A 和 B 之间交换内容?
    • 哦,你的意思是我可以有两个完全独立的布局,然后决定我要膨胀哪一个。但这似乎有点浪费,因为顶级容器是相同的,所以我会有多余的代码。有没有办法只动态改变部分布局,比如 switchig &lt;include&gt;
    猜你喜欢
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    相关资源
    最近更新 更多