Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android DataBinding Dynamic addView

Tags:

android

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

like image 275
CrashHunter Avatar asked Jul 16 '15 06:07

CrashHunter


2 Answers

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!

like image 157
Nari Kim Shin Avatar answered Oct 03 '22 05:10

Nari Kim Shin


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.

like image 31
lvqiang Avatar answered Oct 03 '22 05:10

lvqiang