2

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/. "

JPM
  • 9,077
  • 13
  • 78
  • 137

2 Answers2

1

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

JPM
  • 9,077
  • 13
  • 78
  • 137
0

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.

  • Sarah Multitasker, a link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it is there, then quote the most relevant part of the page you are linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted.](/help/deleted-answers) – Yunnosch Aug 09 '23 at 11:23