Open In App

How to Detect Touch Event on Screen Programmatically in Android?

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Games: Most of the games come with touch listeners, that invoke different functions upon different touch applications.
  2. 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.

Detect Touch on Screen

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.Bundle
import android.view.MotionEvent
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import 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)
        }
    }
}


Output: Run on Physical Device

Detect Touch in a Sub-Class View

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: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.SuppressLint
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import 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
            }
        }
    }
}


Output: Run on Physical Device

Detect Touch on Multiple Views

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: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.SuppressLint
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import 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)
    }
}


Output: Run on Physical Device



Last Updated : 23 Feb, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads