How to Detect Touch Event on Screen Programmatically in Android?
Last Updated :
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.
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)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
return when (MotionEventCompat.getActionMasked(event)) {
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
android:id = "@+id/main_view"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< 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)
val v1 = findViewById<View>(R.id.view1)
v1.setOnTouchListener { v, event ->
return @setOnTouchListener when (MotionEventCompat.getActionMasked(event)) {
MotionEvent.ACTION_DOWN -> {
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
android:id = "@+id/main_view"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< 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)
val mainView = findViewById<View>(R.id.main_view)
val subView = findViewById<View>(R.id.view1)
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
}
}
}
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
Similar Reads
How to Detect Tablet or Phone in Android Programmatically?
A Mobile is a portable electronic device that allows you to make calls, send messages, and access the internet, among other functions. A tablet is a mobile computing device with a touchscreen display and typically a larger screen size than a smartphone. Both devices are designed to be portable and a
3 min read
How to Take Screenshot Programmatically in Android?
In every android phone, we have feature to take screenshots of screens. In this article, we are going to explain how to take screenshots programmatically. Step-by-Step ImplementationStep 1: Create a New ProjectTo create a new project in Android Studio please refer to How to Create/Start a New Projec
4 min read
How to Find the Screen Resolution of a Device Programmatically in Android?
Screen Resolution refers to the number of pixels on display. A higher resolution means more pixels and more pixels provide the ability to display more visual information. This entity is widely used in applications related to the broadcasting of real-time visuals such as live video, gaming, etc for o
3 min read
How to Programmatically Take a Screenshot on Android?
Ever wanted to take some perfect screenshot of a particular view, or perhaps some UI element ruined your favorite screenshot? Don't worry much, this Geeks for Geeks article will help you achieve it by making an app from scratch. As Below is the code for the title name in this article, we are going t
3 min read
How to Find Dots-Per-Inch (DPI) of Screen in Android Programmatically?
Dots-Per-Inch or DPI is a measure of pixel density over the physical area on the screen. A pixel is the smallest unit of any screen display. and the sum of all the pixels present on the screen is termed as Screen Resolution. The pixels available to the user are called Viewport and in this article, w
2 min read
How to Fetch Device ID in Android Programmatically?
The android Device ID is a unique code, string combinations of alphabets and numbers, given to every manufactured android device. This code is used to identify and track each android device present in the world. In Android, the Device ID is typically related to the Google Play Services and is most c
3 min read
How to Get the Device's IMEI and ESN Programmatically in Android?
Many times while building Android Applications we require a unique identifier to identify the specific mobile users. For identifying that user we use a unique address or identity. For generating that unique identity we can use the android device id. In this article, we will take a look at How to get
4 min read
How to Change the Screen Orientation Programmatically using a Button in Android?
Generally, the screen orientation of any application is Portrait styled. But when it comes to gaming or any other multimedia service such as watching a video, the screen orientation must change functionally from Portrait to landscape or vice-versa when the functionality is not required. So a develop
3 min read
How to Get RAM Memory in Android Programmatically?
RAM (Random Access Memory) of a device is a system that is used to store data or information for immediate use by any application that runs on the device. Every electronic device that runs a program as a part of its application has some amount of RAM associated with it. Mobile devices nowadays come
3 min read
How to Vibrate a Device Programmatically in Android?
Hepatic feedback are also considered when it comes to user experience. So in this discussion, it's been discussed various types of haptics or the types of vibration of the device. For example, click haptics or long-press button haptics. There five different types of vibration modes in haptic feedbac
7 min read