Last active
March 23, 2023 09:01
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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