Android DataBinding动态addView

boy*_*yue 3 android

我有两个布局xml AB.

带有id'layout '的A xml中的linearlayout

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

我怎么能通过使用来做到这一点 databinding

Nar*_*hin 8

我不认为这是最好的做法,但这是我动态添加视图的方式databinding.

在布局中A,我有FrameLayout如下所示:

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    bind:createView="@{viewModel.dynamicViews}">
Run Code Online (Sandbox Code Playgroud)

在我的viewModel课上,我有一个带BindingAdapter注释的静态方法,

@BindingAdapter("bind:createView")
public static void createImproveView(FrameLayout layout, LinearLayout replacement) {
    layout.removeAllViews();
    layout.addView(replacement);
}
Run Code Online (Sandbox Code Playgroud)

我在这里有替换布局:

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

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


bor*_*x12 0

如果您想使用布局 xml 执行相同的操作。像这样使用包含控件:

<include layout="@layout/header_logo_lyt" //Name of xml you want to include/>  
Run Code Online (Sandbox Code Playgroud)