Created
June 11, 2019 07:45
-
-
Save rezaiyan/e06d07156dcd18a9ad99cab2143555a6 to your computer and use it in GitHub Desktop.
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.view.MotionEvent | |
import android.view.View | |
import android.view.View.OnTouchListener | |
import java.util.* | |
/** | |
* Detects left and right swipes across a view. | |
*/ | |
class OnSwipeTouchListener : OnTouchListener { | |
var dX: Float = 0.toFloat() | |
var dY: Float = 0.toFloat() | |
var startPointX: Float = 0.toFloat() | |
var startPointY: Float = 0.toFloat() | |
private var startClickTime: Long = 0 | |
private var view: View? = null | |
@SuppressLint("ClickableViewAccessibility") | |
override fun onTouch(view: View, event: MotionEvent): Boolean { | |
this.view = view | |
when (event.action) { | |
MotionEvent.ACTION_DOWN -> { | |
startClickTime = Calendar.getInstance().timeInMillis | |
dX = view.x - event.rawX | |
dY = view.y - event.rawY | |
startPointX = event.rawX | |
startPointY = event.rawY | |
} | |
MotionEvent.ACTION_UP -> { | |
when { | |
(view.x >= view.width / 1.5) -> { | |
setPosition(view, (+view.width).toFloat()) | |
resetPosition(view) | |
} | |
(-view.x >= view.width / 1.5) -> { | |
setPosition(view, (-view.width).toFloat()) | |
resetPosition(view) | |
} | |
else -> { | |
resetPosition(view) | |
} | |
} | |
} | |
MotionEvent.ACTION_MOVE -> { | |
when { | |
Math.abs(event.rawY - startPointY) * 1.5 > Math.abs(event.rawX - startPointX) -> resetPosition( | |
view | |
) | |
else -> resetPosition(view) | |
} | |
} | |
else -> return false | |
} | |
return true | |
} | |
private fun resetPosition(view: View?) { | |
view?.animate()?.x(0F)?.setDuration(200)?.start() | |
} | |
private fun setPosition(view: View?, position: Float) { | |
view?.animate() | |
?.x(position) | |
?.setDuration(200) | |
?.start() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment