Search code examples
androidmvvmandroid-databindingandroid-mvvmandroid-viewbinding

How to set onClick function in xml include layout using viewBinding MVVM


How to achieve onclick event in include layout in MVVM architecture

we have a layout Y includes in layout X

sample layout X (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<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>

        <import type="android.view.View" />
    
        <variable
            name="viewModel"
            type=".view.ViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <include
            android:id="@+id/toolbar"
            layout="@layout/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toTopOf="parent" />
        
    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

sample layout Y (toolbar_layout.xml)

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <import type="android.view.View" />

         <variable
            name="viewModel"
            type=".view.ViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/img_back"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:background="@drawable/circle_white"
            android:onClick="@{(v) -> viewModel.clickEvent()}"
            android:padding="12dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/ic_baseline_arrow_back_24" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

in the above scenario, the click function is not working, how to achieve this with viewBinding without depending on dataBinding?


Solution

  • Your click-function is not working, because the viewModel variable in toolbar_layout.xml (Layout Y) is not set when including it into activity_mail.xml (Layout X).

    You can set the variable like this:

    <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar_layout"
                bind:viewModel="@{viewModel}"
                ... />
    

    Link to documentation.

    update: binding the variable