由于视图绑定迁移导致代码重复

问题描述

我正在尝试从 kotlin 合成迁移到推荐的视图绑定模式。为了减少锅炉代码,我选择使用 here 中的委托方法

现在我面临一个问题,我不知道如何以优雅的方式解决它。我有两个类似的布局,它们仅与几个视图不同。例如,假设 layout_alayout_b

    <!-- This is just an example (layout_a) ! -->
    <LinearLayout>
        <TextView
            android:id="@+id/commonView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <TextView
            android:id="@+id/commonView2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>
    <!-- This is just an example (layout_b) ! -->
    <LinearLayout>

        <TextView
            android:id="@+id/commonView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <TextView
            android:id="@+id/commonView2"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <TextView
            android:id="@+id/specialView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

因为我不想在我的应用程序中为这些 TextViews 编写两次文本设置器逻辑,所以我创建了一个额外的单例类,通过 view 对象精确映射这些常见视图。多亏了 kotlin 合成,当我使用相同的 ID(如 commonView1commonView2)时,我能够引用这些视图。因为现在我必须使用绑定对象(在本例中为 LayoutABinding 和 LayoutBBinding),所以我不能这样做。

当然,我可以以编程方式更改 specialView1 的可见性并将这两个布局合并为一个,但这种重复的原因是性能和内存效率。当然,上面只是一个例子,在我原来的应用程序中,我有更多的视图会被不必要地渲染并浪费内存空间。

一种可能的解决方法在这些特殊情况下使用 findViewById,这有点像 IMO。

有没有办法抽象这些绑定?

解决方法

对于这种情况,您可以使用 ViewStubViewStub 不会膨胀视图,直到您调用它。这将解决您的性能问题。

有两个 ViewStub 并在运行时膨胀存根。您可以绑定膨胀视图 Like this。拥有 Binding 对象后,您可以直接访问视图。只需将数据对象传递给 Binding 即可在文本视图上显示数据。您在该单例中的任何逻辑都可以与 DataBinding 一起使用。

,

您可以创建一个包含通用视图的自定义视图,这样您将拥有一个绑定类。

另一种方法是使用 import emoji_file # get dict of the module,then extract those items that don’t start with __ names = [item for item in dir(emoji_file) if not item.startswith("__")] my_list = ["grinning_face","rolling_on_the_floor_laughing","winking_face"] # checking if in the my_list.. "grinning_face","rolling_on_the_floor_laughing" and "winking_face" is present in emoji_file. for i in range(len(my_list)): # checks if the uppercase version of the item in my_list at index i is in names if my_list[i].upper() in names: print(f"Present {my_list[i]}") else: print("Not present") 将公共视图包含到两个布局中。