Android数据绑定动态添加视图

9

我有两个布局XML文件, AB

A XML文件中有一个id为'layout'的LinearLayout

现在我想使用layout.addView()B添加到布局中

如何使用databinding实现这个功能呢?

3个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
9
我认为这不是最佳实践,但以下是我如何使用数据绑定动态添加视图的方法。 在布局A中,我有一个类似下面的FrameLayout: ```xml ```
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    bind:createView="@{viewModel.dynamicViews}">
在我的viewModel类中,我有一个带有BindingAdapter注解的静态方法。
@BindingAdapter("bind:createView")
public static void createImproveView(FrameLayout layout, LinearLayout replacement) {
    layout.removeAllViews();
    layout.addView(replacement);
}

我已经有了我的替代布局:

public LinearLayout getDynamicViews() {
    LinearLayout layout = new LinearLayout(mContext);
    // dynamically add views here. This could be your layout B.
    return layout;
}

我找不到其他解决方案,这个对我来说很好用。请给我任何意见,我愿意学习更好的解决方案!


你在哪个类中添加了getDynamicViews()方法?我很好奇,因为它使用了上下文。 - Rakesh

3

addView(databinding.getRoot())
你可以看到getRoot()返回一个View实例,因此你可以使用这种方法addView

这个databinding是你想要添加的视图的databinding实例。


我认为这比最受欢迎的答案更好,因为视图模型应该负责数据创建,并且不应引用上下文,这意味着在视图模型中拥有视图是不可行的,因此我们必须回到旧的直接方法。 - cutiko

0
如果您想使用布局 XML 来完成相同的操作,请使用 include 控件,如下所示:
<include layout="@layout/header_logo_lyt" //Name of xml you want to include/>  

Include不是数据绑定。 - cutiko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,