How to Detect Touch Event on Screen Programmatically in Android?

23 Feb, 2021
Detecting a touch confirms that the screen is fully functional. Responding to touch is something that a developer deals with. As Android devices have a touch-based input, things are programmed upon application of touch. For explicitly calling methods within the application, a touch action must be recognized. Such methods can have special functions. Common applications that use such special functions are:
Games: Most of the games come with touch listeners, that invoke different functions upon different touch applications.Lock Screen: Screen Locks are generally touched movement-based, where a single tap doesn’t unlock the device. Rather, a pattern or a swipe has to be made by the user to unlock the device. Ex: Pattern-based locks, swipe locks.
Games: Most of the games come with touch listeners, that invoke different functions upon different touch applications.
Lock Screen: Screen Locks are generally touched movement-based, where a single tap doesn’t unlock the device. Rather, a pattern or a swipe has to be made by the user to unlock the device. Ex: Pattern-based locks, swipe locks.
Note that we are going to implement this project using the Kotlin language.
To check if there were touch movements on a screen in Android, we shall follow the following steps:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. There are no changes made to the activity_main.xml file. 
Step 2: Working with the MainActivity.kt file
Finally, 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.
Kotlin
import android.os.Bundleimport android.view.MotionEventimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.core.view.MotionEventCompat  class MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)        // Do Nothing    }          // create an override function onTouchEvent that takes    // in the MotionEvent and returns a boolean value    override fun onTouchEvent(event: MotionEvent): Boolean {        return when (MotionEventCompat.getActionMasked(event)) {              // Display a Toast whenever a movement is captured on the screen            MotionEvent.ACTION_MOVE -> {                Toast.makeText(applicationContext, "Action was MOVE", Toast.LENGTH_SHORT).show()                true            }            else -> super.onTouchEvent(event)        }    }}
To check if there were touch movements in a specific view displayed on a screen in Android, we shall follow the following steps:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file which represents the UI of the application, and create a LinearLayout, give it a dark background, and no other elements so that we can see the touch impressions. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/main_view"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">      <!--View (Sub-Class) where OnTouchListener is implemented-->    <LinearLayout        android:id="@+id/view1"        android:layout_width="300sp"        android:layout_height="400sp"        android:layout_centerInParent="true"        android:background="@color/colorPrimaryDark"        android:orientation="horizontal">    </LinearLayout>      </RelativeLayout>
Step 3: Working with the MainActivity.kt file
Finally, 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.
Kotlin
import android.annotation.SuppressLintimport android.os.Bundleimport android.view.MotionEventimport android.view.Viewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.core.view.MotionEventCompat  class MainActivity : AppCompatActivity() {    @SuppressLint("ClickableViewAccessibility")    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // View (Sub-Class) where onTouchEvent is implemented        val v1 = findViewById<View>(R.id.view1)          // OnTouchListener on the selected view        v1.setOnTouchListener { v, event ->              return@setOnTouchListener when (MotionEventCompat.getActionMasked(event)) {                MotionEvent.ACTION_DOWN -> {                      // Make a Toast when movements captured on the sub-class                    Toast.makeText(applicationContext, "Move", Toast.LENGTH_SHORT).show()                    true                }                else -> false            }        }    }}
To check if there were touch movements in multiple views displayed on a screen in Android, we shall follow the following steps:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file which represents the UI of the application, and create a LinearLayout, give it a dark background, and no other elements so that we can see the touch impressions. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/main_view"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">      <!--View (Sub-Class) where OnTouchListener is implemented-->    <LinearLayout        android:id="@+id/view1"        android:layout_width="300sp"        android:layout_height="400sp"        android:layout_centerInParent="true"        android:background="@color/colorPrimaryDark"        android:orientation="horizontal">    </LinearLayout>      </RelativeLayout>
Step 3: Working with the MainActivity.kt file
Finally, 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.
Kotlin
import android.annotation.SuppressLintimport android.os.Bundleimport android.view.MotionEventimport android.view.Viewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.core.view.MotionEventCompat  class MainActivity : AppCompatActivity() {    @SuppressLint("ClickableViewAccessibility")    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // mainView is nothing but the parent activity_main layout        // subView is a explicitly declared Linear         // Layout and occupies a minor part of the screen        val mainView = findViewById<View>(R.id.main_view)        val subView = findViewById<View>(R.id.view1)          // OnTouchListener on the Screen        mainView.setOnTouchListener { v, event ->            return@setOnTouchListener when (MotionEventCompat.getActionMasked                (event)) {                MotionEvent.ACTION_DOWN -> {                    if (isInside(subView, event)) {                        Toast.makeText(applicationContext, "Inside", Toast.LENGTH_SHORT).show()                    }                    if (!isInside(subView, event)) {                        Toast.makeText(applicationContext, "Outside", Toast.LENGTH_SHORT).show()                    }                    true                }                else -> false            }        }    }      // V shall be the subclass i.e. the subView declared in onCreate function    // This functions confirms the dimensions of the view (subView in out program)    private fun isInside(v: View, e: MotionEvent): Boolean {        return !(e.x < 0 || e.y < 0 || e.x > v.measuredWidth ||                e.y > v.measuredHeight)    }}
Android-Misc
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.