jinx3d jinx3d - 1 month ago 26
Android Question

How to check which item was clicked in a recyclerview child

The recyclers child view contains two click-able objects , one is a set of TextViews and ImageView, the other one is a CheckBox
(Refer - Android Recyclerview Multiple onclick items)
I want to see if on the child the checkbox is clicked or not. If so, then I change the state of the CheckBox.
Else, I initiate another activity (for result). The above link shows handling clicks IN the view holder. I would like to handle clicks in one of my other activities where I am setting up the RecyclerView.

//the view needs a listener
final GestureDetector mGestureDetector = new GestureDetector(getActivity(), new GestureDetector.SimpleOnGestureListener() {

@Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}

});


mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());

if(child!=null && mGestureDetector.onTouchEvent(motionEvent)){

if(child.getId() == R.id.chk_box_pin){
//checking, this didn't work
}
else {
TextView idView = (TextView) child.findViewById(R.id.note_id_txt_vw);
if (DEBUG) Toast.makeText(getActivity(),
"ID is " + idView.getText().toString(), Toast.LENGTH_SHORT).show();
startEditNoteActivity(ActivityContract.ACTIVITY_EDIT, idView.getText().toString());
}
return true;
}

return false;
}

@Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {

}
});


Is there a way I could handle clicks on multiple items inside a child in an activity (instead of the ViewHolder) ?

Answer

Unfortunately, you have to implement your own listener to communicate with your activity.

Create an interface, implement it on your activity, pass your interface instance on your adapter (cast the context on your interface) and call your custom method with custom parameters.

Like this you should have access to your ViewHolder (don't forget to use the adapter best practice implementation).

Hope it's helps !

Best.

Check this: Why doesn't RecyclerView have onItemClickListener()? And how RecyclerView is different from Listview?

Comments