Overlay Multiple Images in a Single ImageView in Android
In Android, an image can be displayed inside an ImageView in the layout. ImageView accepts only a single image at a time as input. However, there can be a need to display two or more images in the same ImageView. Let us say, our application shows the status of airplane mode. When airplane mode is enabled, it must display the image of an airplane and when it is disabled, it must overlay the same image with something like a cross or block symbol. As ImageView accepts only a single input source, it is impossible to set two images as the source. So, in such a case, we will have to create a resource that consists of a list of images and set this resource as the source attribute of the ImageView. So, through this article, we will show you how you could create a resource containing multiple images and set it in the ImageView.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Import images of your choice in the drawable folder
We imported two vector assets from the local clip art. Store them in the drawable folder.
Refer to this article: How to Add Image to Drawable Folder in Android Studio?
Step 3: Create a Drawable Resource File with root element as layer-list (layer.xml)
Create a drawable resource file inside the drawable folder with the root element as a layer list. Give it a name like a layer. The generated file has an extension XML.
Step 4: Add items (imported images) to the layer.xml
Add items in such a way that the next item overlaps the previous one.
Step 5: Working with the activity_main.xml file
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. Add ImageView and a button in the layout file. ImageView will display the layer-list upon button click.
Step 6: 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.
We can see that as we click on the overlay button, the ImageView is set with the two images, one overlapping the other.