Simple Moving Object with TouchEvents in Android
Last Updated :
30 Jul, 2024
In this article, we will make an application through which a user can move an object visible on the screen according to his/her finger movements on the screen. Touch to drag/move objects (like image, button) is very popular in games like Jigsaw Puzzles. Here we will create a simple way to touch and drag an image on a device screen after the user finishes this action, the image will have a new location on the device screen by using view onTouchListener. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Basic Project Overview:
Step by Step Implementation
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: Set any image object in the layout
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="@+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="moving object"
android:src="@drawable/gfg" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
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.
Kotlin
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.MotionEvent
import android.view.View.OnTouchListener
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var mainLayout: ViewGroup
private lateinit var image: ImageView
// default position of image
private var xDelta = 0
private var yDelta = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainLayout = findViewById(R.id.main)
image = findViewById(R.id.image)
// returns True if the listener has
// consumed the event, otherwise False.
image.setOnTouchListener(onTouchListener())
}
@SuppressLint("ClickableViewAccessibility")
private fun onTouchListener(): OnTouchListener {
return OnTouchListener { view, event ->
// position information
// about the event by the user
val x = event.rawX.toInt()
val y = event.rawY.toInt()
// detecting user actions on moving
when (event.action and MotionEvent.ACTION_MASK) {
MotionEvent.ACTION_DOWN -> {
val lParams = view.layoutParams as RelativeLayout.LayoutParams
xDelta = x - lParams.leftMargin
yDelta = y - lParams.topMargin
}
MotionEvent.ACTION_UP -> Toast.makeText(this,
"new location!", Toast.LENGTH_SHORT)
.show()
MotionEvent.ACTION_MOVE -> {
// based on x and y coordinates (when moving image)
// and image is placed with it.
val layoutParams = view.layoutParams as RelativeLayout.LayoutParams
layoutParams.leftMargin = x - xDelta
layoutParams.topMargin = y - yDelta
layoutParams.rightMargin = 0
layoutParams.bottomMargin = 0
view.layoutParams = layoutParams
}
}
// reflect the changes on screen
mainLayout.invalidate()
true
}
}
}
Now, run the app.
Output:
Similar Reads
Pick Color From Image with TouchEvents in Android In this article, we are going to learn how to get touched pixel color on an image. A Screenshot is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. Step by Step Implementation Step 1: To create a n
2 min read
Android Gestures with Examples 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
6 min read
Android - Swipe to Delete and Undo in RecyclerView with Kotlin We have seen many android applications in which data is being displayed in the form of a list. If we want to delete any item from that recycler view we can simply swipe that item to delete it. We can see this type of feature in the Gmail application in which when an email is swiped to the right it i
7 min read
Android Sensors with Example In our childhood, we all have played many android games like Moto Racing and Temple run in which by tilting the phone the position of the character changes. So, all these happen because of the sensors present in your Android device. Most Android-powered devices have built-in sensors that measure mot
4 min read
Input Events in Android with Example In Android, there's quite a method to intercept the events from a user's interaction with your application. When considering events within your interface, the approach is to capture the events from the precise View object that the user interacts with. The View class provides the means to try to do s
7 min read