Created
November 22, 2019 03:27
-
-
Save wertgit/55d2c1b960b3a8370cc2d19efdbe4116 to your computer and use it in GitHub Desktop.
A Customed SwipeRefreshLayout that handles swiping issues with a RecyclerView inside a SwipeRefreshLayout. It also works for HorizontalScrollView.
This file contains 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
import android.annotation.SuppressLint | |
import android.content.Context | |
import android.util.AttributeSet | |
import android.view.MotionEvent | |
import android.view.ViewConfiguration | |
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout | |
import kotlin.math.abs | |
/** | |
* Custom SwipeRefreshLayout to avoid swipe conflicts between SwipeRefreshLayout and other views like | |
* RecyclerView item swipes or Horizontal ViewPager scrollview. | |
* Class overrides the onInterceptTouchEvent. | |
* Calculates if the X distance the user has moved is bigger than the touch slop. | |
* If it does, it means the user is swiping horizontally, | |
* therefor the method return false which | |
* lets the child view (RecyclerView for example) to get the touch event. | |
* | |
*/ | |
class CustomSwipeToRefresh(context: Context, attrs: AttributeSet) : | |
SwipeRefreshLayout(context, attrs) { | |
private var mTouchSlop: Int = 0 | |
private var mPrevX: Float = 0.toFloat() | |
// Indicate if we've already declined the move event | |
private var mDeclined: Boolean = false | |
init { | |
mTouchSlop = ViewConfiguration.get(context).scaledTouchSlop | |
} | |
@SuppressLint("Recycle") | |
override | |
fun onInterceptTouchEvent(event: MotionEvent): Boolean { | |
when (event.action) { | |
MotionEvent.ACTION_DOWN -> { | |
mPrevX = MotionEvent.obtain(event).x | |
mDeclined = false // New action | |
} | |
MotionEvent.ACTION_MOVE -> { | |
val eventX = event.x | |
val xDiff = abs(eventX - mPrevX) | |
if (mDeclined || xDiff > mTouchSlop) { | |
mDeclined = true // Memorize | |
return false | |
} | |
} | |
} | |
return super.onInterceptTouchEvent(event) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment