Do Not have
setOnItemClickListener, like ListView/View does.
This can be achieved by using Interface.
This post is incontinuation to this RecyclerView Example.
Before starting any further, Lets have a recap of Interface.
Some of the features(that we shall be using) of an Interface are:
- You can not instantiate a Variable, nor create an Object of an Interface.
- Methods are public, abstract. (No Implementation)
- An Interface reference variable can point to objects of its implementing classes
- Interface variable must be initialized, else the compiler will throw an error.
Steps correspond below image.
Assigning an Implementing Class Object to Interface Variable will be used in this example. This is mainly useful incase, if the Object changes in future, there wont be any other code changes.
If you look at this Click Listener Example, steps involved to create Click Listener are,
- Implementation of View.OnClickListener
Below example is in continuation to RecyclerView Example, so have a look at this RecyclerView Example.
Here, we start with Creating an Interface and an abstract Method.
Create an Interface Variable and Initialize in the Constructor.
Now Implement View.OnClickLisener in the View Holder and Overide OnClick Method, call interface method within.
In the View Holder Constructor, setOnClickListener to the View Item after getting the ID.
From the Activity, Implement the new Interface that is created, and define the abstract method for the required behavior needed when Item gets Clicked. Pass this object to initialize the Interface variable.
Overview of Code:
References: Udacity, Android Developer Document, Code Path, StackOverflow.