Develop apps faster using Data Binding – Part 4

4. Data Binding + Handler

Google has been pushing updates to existing tools and making the life of android developers easier. They also have been releasing new libraries and APIs. “Data binding” is one of them. In this series, we are going to focus on some powerful features of it.

Following are our previous articles if you missed.

  • Part – 1 How to integrate Data Binding library and how to use it in layout file.
  • Part – 2 How to use Data Binding with RecyclerView.
  • Part – 3 How to downlaod images using Picasso with Data Binding.

In this tutorial, we are going to learn how to handle click event with Data Binding.

How to handle Clicks with Data Binding

Step 1

In our previous tutorial, we learnt if we are using andy 3rd party library then we require to create a bridge. Same thing we require to follow while applying listeners.

Create a class UserClickHandler and paste below code.

Here, Snackbar is used. So if you have not imported Design Support Library, use below code in dependencies.

Step 2

Open your user_item.xml layout file and add below lines of code in data tag.

This will declare a new attribute for data binding. You can use handler to provide your click handler to appropriate view. In our case, I am giving this to root view.

Full layout code.

Step 3

This is our last step to finish click handling. We need pass object when CardView is clicked. So that we can perform some operation upon selected object.

Open UserViewHolder class and paste below line of code in bind method.

After adding this line, full class looks like

Output

Download

Source code for this article is available here.

Summary

In this tutorial, you learn how to handle clicks, how to pass selected object to handler and how to perform operation upon.

You may also like to read

Exit from Activity with twice “Back” b... When we are doing some important operation or work on activity and it may possible that by mistake we pressed "back" button. Then what?? This will sim...
APK Analysis : Spotlight on WhatsApp | How to use ... Android Studio includes an APK Analyzer that provides immediate insight into the composition of your APK after the build process is complete. In th...
ProGuard Secure your APK from Reverse Engineering ... Following are words from http://proguard.sourceforge.net who are inventor of it. ProGuard is a free Java class file shrinker, optimizer, obfuscator...
Read Logs programmatically in Android In this blog you will learn how to read logs programmatically in Android and used for bug report purposes. Its easy to read logs from Logcat an...
Share on Facebook13Share on Google+2Tweet about this on TwitterShare on LinkedIn6Share on Reddit0Pin on Pinterest0Share on Tumblr0Email this to someone