Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class SecondFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_second, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<Button>(R.id.button_second).setOnClickListener {
findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
}
val textView = view.findViewById<TextView>(R.id.textview_second)
view.findViewById<ConstraintLayout>(R.id.root)
.touches()
.classifyTouches(500L)
.filterNot { it is Touch.Other }
.onEach {
textView.text = it.javaClass.simpleName
Log.w("ivan", "[SecondFragment][onViewCreated] $it")
}
.launchIn(lifecycleScope)
}
sealed class Touch(open val x: Float, open val y: Float) {
object Click: Touch(0F, 0F)
data class Down(override val x: Float, override val y: Float): Touch(x, y)
data class Move(override val x: Float, override val y: Float): Touch(x, y)
data class Up(override val x: Float, override val y: Float): Touch(x, y)
object Other: Touch(0F, 0F)
}
private fun Flow<MotionEvent>.classifyTouches(clickReactionTime: Long): Flow<Touch> {
var lastDownTime = 0L
var lastX = 0F
var lastY = 0F
val xyThreshold = 3F
return map { event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
lastDownTime = System.currentTimeMillis()
Touch.Down(event.x, event.y)
}
MotionEvent.ACTION_MOVE -> {
val diffX = abs(lastX - event.x)
val diffY = abs(lastY - event.y)
lastX = event.x
lastY = event.y
if (diffX <= xyThreshold && diffY <= xyThreshold) {
Touch.Other
} else {
Touch.Move(event.x, event.y)
}
}
MotionEvent.ACTION_UP -> {
val currentTime = System.currentTimeMillis()
if (currentTime - lastDownTime >= clickReactionTime) {
Touch.Up(event.x, event.y)
} else {
Touch.Click
}
}
else -> Touch.Other
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment