'How to add GestureDetector and ScaleGestureDetector on a ImageView with setOnTouchListener
In my MainActivity i have:
class MainActivity : AppCompatActivity() {
lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val imageViewGestureDetector = GestureDetector( this, object : GestureDetector.SimpleOnGestureListener() {
override fun onDoubleTap(e: MotionEvent?): Boolean {
return true
}
override fun onFling(
e1: MotionEvent?,
e2: MotionEvent?,
velocityX: Float,
velocityY: Float
): Boolean {
Log.i("MainActivity", "Fling!")
return super.onFling(e1, e2, velocityX, velocityY)
}
})
imageView.setOnTouchListener { _, event -> imageViewGestureDetector.onTouchEvent(event) }
}
}
Now I thought it might be nice to define a behaviour for onScale but I noticed Scale Gestures are detected by the ScaleGestureDetector.
I'd rather not sub-class the ImageView and override fun onTouchEvent() - or should I? That's what all of the solutions in the net seem to suggest. I'd assume there might be a convenient way to combine these common gestures in one view.
Solution 1:[1]
I found a quite simple way myself.
I wrote a ScaleGestureDetector like that
val imageViewScaleGestureDetector = ScaleGestureDetector(this, object: ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector?): Boolean {
Log.i(“MainActivity”, “scale”)
return super.onScale(detector)
}
})
and changed the line
imageView.setOnTouchListener { _, event -> imageViewGestureDetector.onTouchEvent(event) }
to
imageView.setOnTouchListener { _, event ->
imageViewScaleGestureDetector.onTouchEvent(event)
imageViewGestureDetector.onTouchEvent(event)
}
My ImageView is detecting both fling and scale gesture. Let me know if that's bad practice or there are better solutions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mario P. Waxenegger |
