4

I want to include a layout with databinding.

I want to pass the id from java to my layout, using an enum, but I cant seem to find out the right syntax.

Here is my Fragment class with the enum and the onCreateView():

private enum TYPE{
    A(R.layout.fragment_item_A),
    B(R.layout.fragment_item_B),
    C(R.layout.fragment_item_C);

    public final int id;
    TYPE(int id) {
        this.id = id;
    }
    private int getId(){
        return id;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //...
    this.type = TYPE.A;
    FragmentItemBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_item, container, false);
    tmpView = binding.getRoot();
    binding.setType(type);
    //...
    return tmpView;
}

I want to inflate R.layout.fragment_item and make it include R.layout.fragment_item_A (or another Type).

Here is my unsuccessful attempt in my R.layout.fragment_item XML file:

<data>
    <variable name="type" type="com.dan.myapp.fragments.MyFragmentClass.TYPE"/>
...
</data>
<include layout="@{type.id}" <!-- layout="@layout/fragment_item_A"-->
         android:id="@+id/included_item"/>

How should I write the binding in the include ?

PS : maybe the answer is in this post or in this one, but I didn't find it...

Community
  • 1
  • 1
Dan Chaltiel
  • 7,811
  • 5
  • 47
  • 92

1 Answers1

3

I am pretty sure that you can't do that. Data Binding requires the layout at compile type so that it can determine types for passing variables and such.

Instead, I think you might do it like this:

<FrameLayout ...>
    <ViewStub android:layout="@layout/fragment_item_a"
              android:visibility="@{type == Type.A ? View.VISIBLE : View.GONE}" .../>
    <ViewStub android:layout="@layout/fragment_item_b"
              android:visibility="@{type == Type.B ? View.VISIBLE : View.GONE}" .../>
    <ViewStub android:layout="@layout/fragment_item_c"
              android:visibility="@{type == Type.C ? View.VISIBLE : View.GONE}" .../>
</FrameLayout>
George Mount
  • 20,708
  • 2
  • 73
  • 61
  • 1
    Too bad, but I guess you're right. Though, I use your code but with only one ViewStub and change the layout programmatically. Works like a charm. Thanks ! – Dan Chaltiel Apr 10 '17 at 09:17