Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Insert Image to Screen at the Touched Coordinates in Android?

  • Last Updated : 25 Aug, 2021

In this article, we are going to learn to place an image on the touched coordinates on the screen. We can insert multiple images on the screen. onTouchListener will be used to get the coordinates of the touched position on the screen so that the image can be inserted at that position. 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. 

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!


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 RelativeLayout 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 version="1.0" encoding="utf-8"?>

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.


import android.annotation.SuppressLint
import android.os.Bundle
import android.view.MotionEvent
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
class MainActivity : AppCompatActivity() {
    lateinit var areaLayout: RelativeLayout
    override fun onCreate(savedInstanceState: Bundle?) {
        areaLayout = findViewById(
        areaLayout.setOnTouchListener { view, event ->
            if (event.action == MotionEvent.ACTION_DOWN) {
                val x = event.x.toInt()  // get x-Coordinate
                val y = event.y.toInt()  // get y-Coordinate
                val lp = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT) // Assuming you use a RelativeLayout
                val iv = ImageView(applicationContext)
                lp.setMargins(x, y, 0, 0) // set margins
                iv.layoutParams = lp
                iv.setImageDrawable(resources.getDrawable(R.drawable.flower)) // set the image from drawable
                (view as ViewGroup).addView(iv) // add a View programmatically to the ViewGroup

Now, run the app


Source Code: Click Here

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!