Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android 2.1 View's getDrawingCache() method always returns null

I'm working with Android 2.1 and have the following problem: Using the method View.getDrawingCache() always returns null. getDrawingCache() should return a Bitmap, which is the presentation of View's content.

Example code:

public void onCreate(final Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

  final View view = findViewById(R.id.ImageView01);
  view.setDrawingCacheEnabled(true);
  view.buildDrawingCache();
  final Bitmap bmp = view.getDrawingCache();
  System.out.println(bmp);

}

I've already tried different ways to configure the View object for generating the drawing cache (e.g. View.setWillNotDraw(boolean) and View.setWillNotCacheDrawing(boolean)), but nothing works.

What is the right way, or what I'm doing wrong?

PS: In real code I want to apply getDrawingCache() on a ViewGroup like RelativeLayout. Is the behaviour the same when using a ViewGroup?

like image 906
Impression Avatar asked May 12 '10 08:05

Impression


3 Answers

Bitmap screenshot;
view.setDrawingCacheEnabled(true);
screenshot = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);

You need Bitmap.createBitmap(view.getDrawingCache()); as the Bitmap from which the reference is received by getDrawingCache() gets recycled.

like image 154
Youyougoslave Avatar answered Nov 09 '22 08:11

Youyougoslave


use

onLayout(x, y, width, height);

for ex:

onLayout(0, 0, 100, 100);

before calling getDrawingCache

like image 22
Vinay Avatar answered Nov 09 '22 09:11

Vinay


Never do these things in onCreate! You can do it in a View.onClickListener or other place.

like image 2
Leox Avatar answered Nov 09 '22 10:11

Leox