Databind Includes Layout

159 Views Asked by At

Trying to dynamically set the layout using databinding but I can't seem to get the ternary operator to work right. Must be missing escape character or something.

<include
    android:id="@+id/setting"
    bind:settingsViewModel="@{settingsViewModel}"
    layout="@{settingsViewModel.configFlag ? @layout/settings_v1 :@layout/settings_v2}" />

Seems simple enough but errors with "****/ data binding error ****msg:included value ... must start with @layout/. "

2

There are 2 best solutions below

0
JPM On BEST ANSWER

The answer to this is that you cannot do this. Layout is called before and so this logic cannot be done before hand.

1
Sarah Multitasker On

You can only solve this by including multiple files and toggling the visibility respectively based on your value you want to bind. An example can be found here: https://stackoverflow.com/a/43289414/11544951 This example uses ViewStubs, but include-tags work just the same way.

So you'd basically do:

<include
layout="@layout/layout_A"
android:visibility="@{viewModel.condition? View.VISIBLE : View.GONE}"
/>

<include
layout="@layout/layout_B"
android:visibility="@{!viewModel.condition? View.VISIBLE : View.GONE}"
/>

This works fine, if the viewmodel for both layouts is the same. If it isn't, check out my solution to this issue: How can I include one layout in another only, if the viewmodel is of a certain subtype with databinding? It shows how to check whether a viewmodel is of a specific type and how to only bind it, if it is.