Open In App

How to Take Sub-View Screenshot in Android?

Last Updated : 23 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Sub-View Screenshot in Android

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: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
    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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads