user5170467
user5170467

Reputation:

How to get specific view checkbox from RecyclerView?

I have a recyclerview filled with relativelayouts each have a textview and a checkbox. In my recyclerview filter fragment I'm Implementing android.widget.CompoundButton.OnCheckedChangeListener to try and differentiate between which textview of the recyclerview item is clicked, then perform an action and the same applies to the unchecking phase, how can this be accomplished?

Thanks

Upvotes: 1

Views: 577

Answers (2)

Harvi Sirja
Harvi Sirja

Reputation: 2492

You can not direct use onclick. I have found a solution and it's works for me. Try it.

Step 1: Fist add this RecyclerItemClickListener class to your package.

public class RecyclerItemClickListener implements
		RecyclerView.OnItemTouchListener {
	private OnItemClickListener mListener;

	public interface OnItemClickListener {
		public void onItemClick(View view, int position);
	}

	GestureDetector mGestureDetector;

	public RecyclerItemClickListener(Context context,
			OnItemClickListener listener) {
		mListener = listener;
		mGestureDetector = new GestureDetector(context,
				new GestureDetector.SimpleOnGestureListener() {
					@Override
					public boolean onSingleTapUp(MotionEvent e) {
						return true;
					}
				});
	}

	@Override
	public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
		View childView = view.findChildViewUnder(e.getX(), e.getY());
		if (childView != null && mListener != null
				&& mGestureDetector.onTouchEvent(e)) {
			mListener.onItemClick(childView,
					view.getChildPosition(childView));
		}
		return false;
	}

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

Step 2: Now use onclick method. this gives you position of item clicked. Once you get position than get view at this position now you can use it as per your requirement.

recyclerview.addOnItemTouchListener(new RecyclerItemClickListener(
				context, new RecyclerItemClickListener.OnItemClickListener() {

	@Override
	public void onItemClick(View view, int position) {
	// TODO Auto-generated method stub

    //find your view at clicked position here.
	CheckBox c = (CheckBox) view.findViewById(R.id.btn_tag);

	if (c.isChecked()) {
          //add your code
	} else {
          //add your code
       }
   }
  }));

Upvotes: 0

justHooman
justHooman

Reputation: 3054

In onCheckedChanged, you can get your relativelayout from your checkbox by checkbox.getParent().
Then you can apply any change to your view.
If you want coresspone position in adapter, you can get by your_recyler_view.getChildAdapterPosition(get_relative_layout)
Hope this helps.

Upvotes: 1

Related Questions