Search code examples
androidonclicklistenerandroid-databinding

How to set a listener functionality (like setOnClickListener) for a view in dataBinding


I'm new in DataBinding concept. I have seen some tutorials but i'm confused by seeing those. Can anyone please give me an idea how to use setOnClickListener or any other listener to a view (eg. Button) using DataBinding. Thanks in advance.

button.setOnClickListener(View v){......} need to use above functionality in dataBinding. Can anyone help me.


Solution

  • If you are using Data-Binding then most probably you are using with some view model if so then do something like this but this concept can be applied to any other variable.

    your xml might look like this.

    <?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>
    
            <variable
                name="viewModel"
                type="com.example.MyViewModel" />
        </data>
    
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            android:paddingStart="16dp"
            android:paddingEnd="16dp">
    
         <!--other views-->
    
            <Button
                    android:id="@+id/btnOkay"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:layout_marginTop="16dp"
                    android:layout_marginEnd="15dp"
                    android:layout_marginBottom="16dp"
                    android:textColor="@color/pdp_black"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:onClick="@{() -> viewModel.onClickOkay()}" />
    
        </androidx.constraintlayout.widget.ConstraintLayout>
    
    </layout>
    

    and in your view model add something like this to receive the callback.

    fun onClickOkay(){
        //from here use some interface to or some live data to notify the view attached with this view model to indicate the click happened in view.
      mutableLiveData.value = true
      //or 
      clickListener.onClick()
    }