I have a complex layout, that should include another layout only, if the viewmodel is of a specific subtype. (e.g. I have four types of entries and one of them has a special layout that others have not.) I cannot only toggle the visibility, as the layout requires the subtype of the viewmodel as a parameter, so some casting needs to happen if it gets included. The layout structure is simplified like that:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="de.example.ui.BaseItemViewModel" />
<import type="android.view.View" />
</data>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
bind:contentPaddingTop="@dimen/item_container_vertical_margin"
bind:contentPaddingBottom="@dimen/item_container_vertical_margin"
android:background="?android:attr/selectableItemBackground"
card_view:cardBackgroundColor="?attr/base_500"
card_view:cardElevation="0dp"
card_view:cardMaxElevation="1dp"
card_view:cardPreventCornerOverlap="false"
card_view:cardUseCompatPadding="true"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
//Many UI elements
<include
android:id="@+id/dependent_layout"
layout="@layout/only_show_if_sub_class"
android:layout_width="0dp"
android:layout_height="@dimen/item_container_view_player_height"
bind:layout_constraintEnd_toStartOf="@id/primary_action"
bind:layout_constraintStart_toStartOf="parent"
bind:layout_constraintTop_toBottomOf="@+id/item_main"
android:layout_marginStart="@dimen/item_image_view_type_icon_margin_start"
android:layout_marginTop="@dimen/item_container_view_player_margin_top"
android:layout_marginEnd="@dimen/item_container_view_player_horizontal_margin"
/>
//More UI
</androidx.cardview.widget.CardView>
</layout>
The sublayout then requires to receive the subclass of the viewmodel:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="de.example.ui.SubtypeViewModel" />
</data>
<RelativeLayout
android:id="@+id/item_player_holder"
android:layout_width="match_parent"
android:layout_height="@dimen/item_container_view_player_height"
>
//UI stuff
</RelativeLayout>
</layout>
How can I achieve that?