Ali Doran
Ali Doran

Reputation: 556

Android MVVM ClickListener best practice

As I read sunflower and many projects we have the multi clean ways for implementing a ClickListener

  1. Binding clicklistener in view (Activity/fragment)
  2. Creating a separated variable for clickListener on XML and call it on the constructor
  3. Creating a static method and calling it from XML
  4. Creating a viewModel with two uses (model and method) and passing the ViewModel class directly to XML and calling the method on our object

1

        binding.addPlant.setOnClickListener {
        navigateToPlantListPage()
    }

2

    <data>
    <variable
        name="clickListener"
        type="android.view.View.OnClickListener"/>
    <variable
        name="plant"
        type="com.google.samples.apps.sunflower.data.Plant"/>
</data>

then

        init {
        binding.setClickListener { view ->
            binding.viewModel?.plantId?.let { plantId ->
                navigateToPlant(plantId, view)
            }
        }
    }

3

    companion object{
    @JvmStatic
    @BindingAdapter("bind:setSubjectText")
    fun setSubjectText(textView: TextView, string: String){
        val mTxt = "Subject: ${string}"
        textView.text = mTxt
    }
}

4

    <data>

    <variable
        name="viewmodel"
        type="com.android.example.livedatabuilder.LiveDataViewModel" />
</data>

as a model

        <TextView
        android:id="@+id/current_weather"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@{viewmodel.currentWeather}"
        tools:text="Tokyo" />

in the same XML as a ViewModel method

        <Button
        android:id="@+id/refresh_button"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:onClick="@{() -> viewmodel.onRefresh()}"
        android:text="@string/refresh_label" />

As you see each of them has some pros and cons. For instance for each theme:

  1. Messy view
  2. When we want to call multi-object in XML, the XML will be messy
  3. In the large-scale program, we will engage with many static methods
  4. Messy ViewModel

Question: which of them is the best practice for implementing clicklistener, especially in large-scale programs with some fragments by many clickable objects?

Upvotes: 0

Views: 241

Answers (1)

Amirhosein
Amirhosein

Reputation: 4446

In my opinion, none of the methods you mentioned were not good anymore, and any new project could use Jetpack Compose. In this fashion, you do not need fragments, XMLs, binding. etc

Upvotes: 1

Related Questions