I am using MVVM android architecture for my application.
I want to implement click event, so, do we need to use data binding architecture components or we can just use activity for handling the click event and validating the user inputs?
What's the best way to implement this?
Well the question would be using the Databinding
or not. Here are some pros and cons of Databinding
:
Pros:
Cons:
But... since Google
has already anounced it as part of the Android Architecture components I believe you should use it.
What's the best way to implement this?
I don't know how familiar you are with the Databinding
but you should know something about Binding Adapters , anw in the onClick
you won't be needing it. Just add the android:onClick
attribute in the XML file. Also you can find this Codelab to properly implement it:
https://codelabs.developers.google.com/codelabs/android-databinding/#0
Example:
First of all make sure you have the Databinding
enabled in your build.gradle
android {
...
dataBinding {
enabled true
}
}
After that go to the layout you will use the databinding (and for that make sure it will be an Activity/Fragment), and just type ALT+ TAB in your IDE and than....
After that, define types, for example a ViewModel
and it's name. And in the view that will use the click function add what I said above. ( android:onClick="@{() -> viewmodel.onLike()}"
)
You are not finished. You will somehow need to connect your logic to that databinding, so go to your Java/Kotlin code for your Activity/Fragment and:
Replace the setContentView(R.layout.some_activity)
with val binding : SomeActivityBinding = DataBindingUtil.setContentView(this, R.layout.some_activity)
Notice the SomeActivityBinding
will be provided by the IDE itself because is handled on the Databinding
library according to the xml naming.
That's the most basic. Good luck.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.