Skip to content

Instantly share code, notes, and snippets.

@projectdelta6
Last active March 23, 2023 09:01
Show Gist options
  • Save projectdelta6/7fbd6fc9ffb778043da243a46d0fd052 to your computer and use it in GitHub Desktop.
Save projectdelta6/7fbd6fc9ffb778043da243a46d0fd052 to your computer and use it in GitHub Desktop.
An implementation of androidx.recyclerview.widget.ListAdapter<T, VH> that provides haptic feedback on scrolling.
//package com.example.app.util
import android.view.HapticFeedbackConstants
import androidx.annotation.CallSuper
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
abstract class HapticScrollListAdapter<T, VH : RecyclerView.ViewHolder>(diffCallback: DiffUtil.ItemCallback<T>) : ListAdapter<T, VH>(diffCallback) {
protected var isScrolling: Boolean = false
/**
* The haptic feedback constant to use when the RecyclerView is scrolling and the ItemView is attached to the window.
* Defaults to [HapticFeedbackConstants.TEXT_HANDLE_MOVE].
*/
open val hapticFeedbackConstant: Int = HapticFeedbackConstants.TEXT_HANDLE_MOVE
@CallSuper
override fun onViewAttachedToWindow(holder: VH) {
super.onViewAttachedToWindow(holder)
if(isScrolling) {
holder.itemView.performHapticFeedback(hapticFeedbackConstant)
}
}
@CallSuper
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
when (newState) {
RecyclerView.SCROLL_STATE_DRAGGING,
RecyclerView.SCROLL_STATE_SETTLING -> {
isScrolling = true
}
RecyclerView.SCROLL_STATE_IDLE -> {
isScrolling = false
}
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment