buradd
buradd

Reputation: 1321

Getting View object of any AlertDialog instance that is visible in current Activity (Android)

I have code that will take a drawing screenshot of the current window's root view.

The problem is, the screenshot is only taken of the activity that is running. It does not draw any AlertDialog that may be visible inside the activity.

Is there a way that I can get a screen drawn of the current activity and any other visible AlertDialogs/Views?

Current code:

 View v1 = getWindow().getDecorView().getRootView();
 v1.setDrawingCacheEnabled(true);
 Bitmap bitmap = Bitmap.createScaledBitmap(v1.getDrawingCache(), 360, 740, false);
 v1.setDrawingCacheEnabled(false);

Upvotes: 1

Views: 127

Answers (1)

Anupam
Anupam

Reputation: 2853

Implement the screenshot method like this -

Pass your alertDialog to capture() method -

private void capture(AlertDialog dialog) {
    Date time = new Date();
    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", time);

    try {
        // image path
        String mPath = "/data/data/com.example.sample/" + time + ".jpg"; // 

        View v1 = dialog.getWindow().getDecorView().getRootView();

        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        File imageFile = new File(mPath);

        FileOutputStream outputStream = new FileOutputStream(imageFile);
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        outputStream.flush();
        outputStream.close();

    } catch (Throwable e) {
        e.printStackTrace();
    }
}

You can create screenshot for any other view by passing that view to this method and change the view v1 based on your requirement.

Upvotes: 1

Related Questions