How to pass a constant to onClick listener in android data binding

  android, data-binding, mvvm

I am just getting into the android MVVM. In my project, I have 3 TextViews that will work as a radio group.

enter image description here

In the above image, any of the options will be selected at a time.

The XML for this is

<data>
    <variable
        name="viewModel"
        type="com.builders.aimsfinance.ui.common.newcandidate.NewCandidateViewModel" />
</data>
   **** Some XML *****
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/candidateSite"
            android:text="Site"
            android:onClick="@{()-> viewModel.setCandidateType()}"
            android:textAlignment="center"
            android:padding="5dp"
            android:layout_margin="5dp"
            android:textColor="@color/purple_700"
            android:background="@drawable/big_rounded_rectangle"
            android:backgroundTint="@color/purple_700"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/candidateShop"
            android:text="Shop"
            android:onClick="@{()-> viewModel.setCandidateType()}"
            android:textAlignment="center"
            android:padding="5dp"
            android:layout_margin="5dp"
            android:textColor="@color/purple_700"
            android:background="@drawable/big_rounded_rectangle"
            android:backgroundTint="@color/purple_700"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/candidateEmployee"
            android:text="Employee"
            android:onClick="@{()-> viewModel.setCandidateType()}"
            android:textAlignment="center"
            android:padding="5dp"
            android:layout_margin="5dp"
            android:textColor="@color/purple_700"
            android:background="@drawable/big_rounded_rectangle"
            android:backgroundTint="@color/purple_700"/>

   **** Some XML *****

and in my ViewModel, I have implemented the following function

class NewCandidateViewModel() : ViewModel() {
    var typ = MutableLiveData<Int>()

    fun setCandidateType(type: Int) {
        typ.value = type
    }
}

Here I set a common handler function viewModel.setCandidateType() for all the TextViews and I have to pass a specific integer on clicking each TextViews. Passing hardcoded value like viewModel.setCandidateType(1) is working fine. But I don’t think this is a proper solution.

My doubt is, how to pass this type of custom values to this handler function from the XML? What is the correct way to do this?

Source: Android Questions

LEAVE A COMMENT