Skip to content

Instantly share code, notes, and snippets.

@frapontillo
Last active August 31, 2019 13:28
Show Gist options
  • Save frapontillo/39a96dc756aff61b64cb to your computer and use it in GitHub Desktop.
Save frapontillo/39a96dc756aff61b64cb to your computer and use it in GitHub Desktop.
How to use SwitchCompat inside a RecyclerView item
// omissis
@Override
public void onBindViewHolder(final CustomViewHolder holder, final int position) {
holder.mSwitch.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
// TODO: handle your switch toggling logic here
}
});
// Listen to touch events on the Switch and, when a tap or drag is starting (ACTION_DOWN),
// disallow the interception of touch events on the ViewParent (valid until an ACTION_UP).
holder.mSwitch.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
holder.mSwitch.getParent().requestDisallowInterceptTouchEvent(true);
}
// always return false since we don't care about handling tapping, flinging, etc.
return false;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment