The drawing cache saves a bitmap of what's currently drawn on screen. Naturally, this does not include hidden views.
The key difference between the article you provided in the link, and your code is that in the article, the bitmap cache is constructed for the invisible view.
However, you have a visible parent, which contains invisible views. When you create the drawing cache of the parent, the invisible views are, of course, not rendered.
In order for you invisible views to appear, you need to draw the views yourself in a bitmap, then draw that bitmap inside the bitmap which contins the parent.
Code sample:
//these fields should be initialized before using
TextView invisibleTextView1;
TextView invisibleTextView2;
ImageView invisibleImageView;
private Bitmap getBitmap(View v) {
Bitmap bmp = null;
Bitmap b1 = null;
RelativeLayout targetView = (RelativeLayout) v;
targetView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
targetView.buildDrawingCache();
b1 = targetView.getDrawingCache();
bmp = b1.copy(Bitmap.Config.ARGB_8888, true);
targetView.destroyDrawingCache();
//create a canvas which will be used to draw the invisible views
//inside the bitmap returned from the drawing cache
Canvas fullCanvas = new Canvas(bmp);
//create a list of invisible views
List<View> invisibleViews = Arrays.asList(invisibleTextView1, invisibleImageView, invisibleTextView2);
//iterate over the invisible views list
for (View invisibleView : invisibleViews) {
//create a bitmap the size of the current invisible view
//in this bitmap the view will draw itself
Bitmap invisibleViewBitmap = Bitmap.createBitmap(invisibleView.getWidth(), invisibleView.getHeight(), Bitmap.Config.ARGB_8888);
//wrap the bitmap in a canvas. in this canvas the view will draw itself when calling "draw"
Canvas invisibleViewCanvas = new Canvas(invisibleViewBitmap);
//instruct the invisible view to draw itself in the canvas we created
invisibleView.draw(invisibleViewCanvas);
//the view drew itself in the invisibleViewCanvas, which in term modified the invisibleViewBitmap
//now, draw the invisibleViewBitmap in the fullCanvas, at the view's position
fullCanvas.drawBitmap(invisibleViewBitmap, invisibleView.getLeft(), invisibleView.getTop(), null);
//finally recycle the invisibleViewBitmap
invisibleViewBitmap.recycle();
}
return bmp;
}
Final mentions:
- if your invisible views have visibility = View.GONE, you should
layout(...)
on each one, before calling draw(...)
in the loop.
if the parent view of your invisible views does not occupy the whole screen, then your invisible views will not be drawn at the correct position, since getLeft()
& getTop()
return the left & top properties in pixels, relative to the parent location. If your invisible views are within a parent which only covers part of the screen, then use instead:
fullCanvas.drawBitmap(invisibleViewBitmap, invisibleView.getLeft() + parent.getLeft(), v.getTop() + v.getTop(), null);
Let me know if this works!