Created
October 12, 2020 07:03
-
-
Save ivanisidrowu/f0f2b091855e1b677bb04cb827fdc1d6 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
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