I have two layout xml A and B
A linearlayout in A xml with id 'layout'
Now I want to add B in layout using layout.addView()
How can i do this by using databinding
I don't think this is the best practice, but here's how I dynamically added views with databinding
.
In layout A
, I have a FrameLayout
like below:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
bind:createView="@{viewModel.dynamicViews}">
In my viewModel
class, I have a static method with BindingAdapter
annotation,
@BindingAdapter("bind:createView")
public static void createImproveView(FrameLayout layout, LinearLayout replacement) {
layout.removeAllViews();
layout.addView(replacement);
}
and I have my replacement layout here:
public LinearLayout getDynamicViews() {
LinearLayout layout = new LinearLayout(mContext);
// dynamically add views here. This could be your layout B.
return layout;
}
I couldn't find any other solutions, and this was working fine for me. Please give me any comments, I'm open to learn better solutions!
addView(databinding.getRoot())
you can see the getRoot()
return a View
instance, so you can addView
by this method.
This databinding is the databinding instance of the view you want to add.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With