How to Take Sub-View Screenshot in Android?
Last Updated :
23 Jan, 2022
A Sub-view in Android can be any UI element present on the screen that has a parent layout or a parent view. It is simply a view inside a view. Assuming, we create a TextView in our activity. As this TextView is present inside the main layout, it is a sub-view of the main layout. Similarly, other elements present inside a layout are its sub-views. Sub-view screenshots are used as acknowledgments in a wide variety of applications. In payment applications, the screenshot of a layout displaying transaction details can be used as a reference receipt for sharing. Similarly, in games, a layout displaying high scores, ranks, stats, etc. is used for sharing over social applications.
So in this article, we will show you how you could take a screenshot of a sub-view in Android. Below are the steps to be followed once the IDE is ready.
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: 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. We shall be taking the screenshot of the TextView which is our sub-view, so we are declaring the TextView in our activity layout. A button is created to perform an action to take the screenshot.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view_1"
android:layout_width="300sp"
android:layout_height="100sp"
android:layout_centerInParent="true"
android:text="GeeksforGeeks"
android:gravity="center"
android:background="#0f9d58"/>
<Button
android:id="@+id/button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Take Screenshot"
android:layout_below="@id/text_view_1"
android:layout_marginTop="20sp"/>
</RelativeLayout>
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. In the main code below, we have implemented methods to take the sub-view screenshot and save it on the device. To save the generated image, a function is developed to save the image on the device. Do refer to Circular Crop an Image and Save it to the File in Android to understand how an image can be stored on the device. Comments are added inside the code to understand the code in more detail.
Kotlin
package org.geeksforgeeks.subviewscreenshot
import android.content.ContentValues
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Declaring and initializing the TextView
// and the Button from the layout file
val mTextView = findViewById<TextView>(R.id.text_view_1)
val mButton = findViewById<Button>(R.id.button_1)
// When button is clicked, screenshot is taken and
// stored in the device using the function created below.
mButton.setOnClickListener {
mTextView.isDrawingCacheEnabled = true
mTextView.buildDrawingCache(true)
val b = Bitmap.createBitmap(mTextView.drawingCache)
mTextView.isDrawingCacheEnabled = false
saveMediaToStorage(b)
}
}
// Function to save an Image
// https://www.geeksforgeeks.org/circular-crop-an-image-and-save-it-to-the-file-in-android/
private fun saveMediaToStorage(bitmap: Bitmap) {
val filename = "${System.currentTimeMillis()}.jpg"
var fos: OutputStream? = null
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
this.contentResolver?.also { resolver ->
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
}
val imageUri: Uri? = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
fos = imageUri?.let { resolver.openOutputStream(it) }
}
} else {
val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
val image = File(imagesDir, filename)
fos = FileOutputStream(image)
}
fos?.use {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
Toast.makeText(this , "Captured View and saved to Gallery" , Toast.LENGTH_SHORT).show()
}
}
}
Output:
You can see that when the button is clicked, the screenshot is taken and stored on the device. Below is the preview of the output.
Similar Reads
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 Implement OTP View in Android?
An OTP View or PinView in android is a widget that allows users to enter their PIN, OTP, etc. They are generally used for two-factor authentication or phone number verification by OTP. A sample video is given below to get an idea about what we are going to do in this article. Note: In order to imple
2 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 Use Photo Picker in Android 13?
With Android 13, Google unveiled a new specialized media picker. This new option provides a more private and user-friendly alternative for those times when you want to share photographs, as opposed to potentially granting apps access to all of your files via the well-known document picker. You don't
4 min read
How to scale different Views to all screen sizes in Android Studio?
In this article, it is shown how to change the size of View in Android App Development (like TextView, etc), so that they can modify the content that is displayed on the screen. Note: For this article, XML visualizer instead of Android Studio. Below are the various methods to change the size of View
4 min read
How to Use Proximity Sensor in Android?
Proximity Sensor is one of the sensors present in mobile devices which we use almost every day. This sensor is present in the top section of your phone. The sensor is used to detect the presence of any object in the proximity of the phone. This sensor is used in many calling apps when the user keeps
3 min read
How to Capture Screenshot of a View and Save it to Gallery in Android?
In this article, we will capture a screenshot of a view and store the image in the gallery. A sample video 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: Cre
4 min read
ProtractorView in Android
In this article, ProtractorView is added to android. ProtractorView is a semicircular Seekbar view for selecting an angle from 0° to 180. Seek bar is a type of progress bar. Change the cursor from 0° to 180 for selecting an angle. Below is the image of ProtractorView. Step By Step ImplementationStep
3 min read
How to Play Videos on TextureView in Android?
TextureView in Android is used to display content streams that can be an instance of a video or an OpenGL scene. The source could be local as well as on the Internet. This view behaves as a regular view without creating a separate window and can only be used in a hardware-accelerated window. So in t
3 min read
How to Implement TNImage Library in Android?
Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android has been one of the best-selling OS for smartphones. Android O
3 min read