Item Click For Recycler View
I am trying to implement on item click for different items that i pop up in RecyclerView. I achieved that in listView but RecyclerView seem to be difficult. I have look at similar
Solution 1:
MainActivity.java
publicinterfaceClickListener {
voidonClick(View view, int position);
voidonLongClick(View view, int position);
}
publicstaticclassRecyclerTouchListenerimplementsRecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private MainActivity.ClickListener clickListener;
publicRecyclerTouchListener(Context context, final RecyclerView recyclerView, final MainActivity.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = newGestureDetector(context, newGestureDetector.SimpleOnGestureListener() {
@OverridepublicbooleanonSingleTapUp(MotionEvent e) {
returntrue;
}
@OverridepublicvoidonLongPress(MotionEvent e) {
Viewchild= recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
@OverridepublicbooleanonInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
Viewchild= rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
returnfalse;
}
@OverridepublicvoidonTouchEvent(RecyclerView rv, MotionEvent e) {
}
@OverridepublicvoidonRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
And
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new ClickListener() {
@Override
public void onClick(View view, int position) {
Movie movie = movieList.get(position);
Toast.makeText(getApplicationContext(), movie.getTitle() + " is selected!", Toast.LENGTH_SHORT).show();
}
@Override
public void onLongClick(View view, int position) {
}
}));
You have to make an interface and have you use GestureDetector
to detect the view has been clicked!
Please note that its just an example to give hints to you
Just try to know yourself what is happening in this code and what you need is what you want. You can edit and reuse this example for you.
Solution 2:
You can bind the onClickListener
to itemView
, like this:
@OverridepublicvoidonBindViewHolder(ExampleViewHolder holder, int position) {
finalExampleModelmodel= mModels.get(position);
holder.bind(model);
holder.itemView.setOnClickListener( ... {
if(position == 1){
...
}else{
...
}
});
}
or do it in ExampleViewHolder.bind()
, then you can pass an argument to it like position
.
Solution 3:
You can add the setOnClickListener
in the onBindViewHolder
of your Adapter and use your model
variable there
Post a Comment for "Item Click For Recycler View"