Blog Infos
Author
Published
Topics
,
Published
enum class SwipeDirection {
ALL, // swipe allowed in left and right both directions
LEFT, // swipe allowed in only Left direction
RIGHT, // only right
NONE // swipe is disabled completely
}

This enum enables us to specify directions in which a user is allowed to swipe at any given point in time. Now we need to create a function that takes MotionEvent object and attempts to detect the direction user is trying to swipe. It should then compare it with the currently set SwipeDirectionand return true if the user’s intention and current setting match or falseotherwise. Here is that function

private fun isSwipeAllowed(event: MotionEvent): Boolean {
if (direction === SwipeDirection.ALL) return true
if (direction == SwipeDirection.NONE) //disable any swipe
return false
if (event.action == MotionEvent.ACTION_DOWN) {
initialXValue = event.x
return true
}
if (event.action == MotionEvent.ACTION_MOVE) {
try {
val diffX: Float = event.x - initialXValue
if (diffX > 0 && direction == SwipeDirection.RIGHT) {
// swipe from left to right detected
return false
} else if (diffX < 0 && direction == SwipeDirection.LEFT) {
// swipe from right to left detected
return false
}
} catch (exception: Exception) {
exception.printStackTrace()
}
}
return true
}
swipeControlTouchListener.setSwipeDirection(SwipeDirection.LEFT)
view raw SetSwipeDir.kt hosted with ❤ by GitHub

Job Offers

Job Offers

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

No results found.

Jobs

Now here is a little hacky part where I had to get access to ViewPager2 to RecyclerView in a questionable way.

// apply touch listener on ViewPager RecyclerView
val recyclerView = binding.viewPager[0] as? RecyclerView
if (recyclerView != null) {
recyclerView.addOnItemTouchListener(swipeControlTouchListener)
} else {
Log.w(localClassName, "RecyclerView is null, API/Version changed ?!")
}

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
It’s one of the common UX across apps to provide swipe to dismiss so…
READ MORE
blog
In this part of our series on introducing Jetpack Compose into an existing project,…
READ MORE
blog
This is the second article in an article series that will discuss the dependency…
READ MORE
blog
Let’s suppose that for some reason we are interested in doing some tests with…
READ MORE
Menu