![]() |
VOOZH | about |
Android supports a range of touch gestures such as tap, double-tap, pinch, swipe, scroll, long press, drag, and fling. Drag and fling may seem similar but drag is the type of scrolling that occurs when a user drags their finger across the touchscreen, while a fling gesture occurs when the user drags and then lifts their finger quickly. A MotionEvent describes the state of touch event via an action code. A long list of action codes is supported by Android:
Note: You should perform same action during ACTION_CANCEL and ACTION_UP event.
Let us see the way to perform some simple actions on events like ACTION_DOWN, ACTION_UP, etc.
Step 1: Create a New Project
To create a new project in Android Studio, refer to How to Create/Start a New Project in Android Studio. Select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Note: You may get an error on the following line:
import kotlinx.android.synthetic.main.activity_main.*
Please refer to this to fix this error.
Explanation of Output:
Now let us see the way to perform some actions on events like single tap, double-tap, long press, etc. The below code uses the same activity_main.xml as used above.
Working with the MainActivity.kt file:
Explanation of Output:
Note: onTouchEvent() is for the activity but you can attach a View.OnTouchListener object to any View object using the setOnTouchListener() method.
By this method, you can perform actions when events are triggered inside a view because OnTouchListener is attached to that particular view. For example, for an ImageView with id "imp".
img.setOnTouchListener { view, motionEvent ->
// ... Respond to touch events
true
}
// for general view
findViewById<View>(R.id.my_view).setOnTouchListener { v, event ->
// ... Respond to touch events
true
}