পূর্ব প্রস্তুতি
এই উদাহরণটি দেখায় কিভাবে একটি ভিউর রুট ভিউ থেকে প্রোগ্রামেটিক্যালি স্ক্রিনশট নেওয়া যায় এবং তা একটি ImageView-এ দেখানো যায়।
ধাপ ১: নতুন প্রজেক্ট তৈরি করুন
Android Studio-তে File → New Project থেকে প্রজেক্ট শুরু করুন।
ধাপ ২: activity_main.xml লেআউট
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="Take screenshot" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:scaleType="fitCenter" />
</RelativeLayout>
ধাপ ৩: MainActivity.kt-এ স্ক্রিনশট লজিক
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
private lateinit var main: View
private lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
main = findViewById(R.id.main)
imageView = findViewById(R.id.imageView)
val btn: Button = findViewById(R.id.button)
btn.setOnClickListener {
val bitmap = Screenshot.takeScreenshotOfRootView(imageView)
imageView.setImageBitmap(bitmap)
main.setBackgroundColor(Color.parseColor("#999999"))
}
}
companion object Screenshot {
private fun takeScreenshot(view: View): Bitmap {
view.isDrawingCacheEnabled = true
view.buildDrawingCache(true)
val bitmap = Bitmap.createBitmap(view.drawingCache)
view.isDrawingCacheEnabled = false
return bitmap
}
fun takeScreenshotOfRootView(v: View): Bitmap {
return takeScreenshot(v.rootView)
}
}
}
ধাপ ৪: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.screenshotdemo">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
পরীক্ষা করুন
অ্যাপ্লিকেশন চালু করুন, "Take screenshot" বাটনে ক্লিক করুন। স্ক্রিনশট নেওয়ার পর তা ImageView-এ প্রদর্শিত হবে এবং ব্যাকগ্রাউন্ড রঙ পরিবর্তন হবে।