0

How to do it? In API level 17 I used:

int color = ((ColorDrawable) activityLayout.getBackground()).getColor();

But ColorDrawable method getColor() added in API level 11 and so I cannot use this method.

Sorry for my English.

Thanks

leonidandand
  • 115
  • 1
  • 11

1 Answers1

9

This may look stupid, but I suggest to draw the ColorDrawable over 1 pixel dimension bitmap and get the pixel color in the bitmap using bitmap.getPixel(0, 0);

// Sample Code

  ColorDrawable colorDrawable=((ColorDrawable) activityLayout.getBackground());

  Bitmap bitmap= Bitmap.createBitmap(1, 1, Config.ARGB_4444);
  Canvas canvas= new Canvas(bitmap);
  colorDrawable.draw(canvas);   
  int pix = bitmap.getPixel(0, 0);
  bitmap.recycle();
rpattabi
  • 9,984
  • 5
  • 45
  • 53
Mohammad Ersan
  • 12,304
  • 8
  • 54
  • 77
  • 1
    Do I need to release any resources after obtaining color of a pixel? May be I should delete Bitmap or Canvas object ? – leonidandand Apr 12 '13 at 23:46
  • yeah, you can **recycle** the `Bitmap`, using `bitmap.recycle();` – Mohammad Ersan Apr 13 '13 at 00:04
  • 1
    This feels so dirty to use... but I'm totally using it. :) I don't see a better option short of reflection (which I avoid if at all possible since you can't trust that the structure has remained the same). I'm always amazed at the simple getters like this that seem to be missing all over the place in lower API levels. – Kevin Coppock Aug 29 '13 at 01:41
  • I found useful the answers here (both get and set) http://stackoverflow.com/questions/21795920/get-background-color-from-textview-without-using-colordrawable-api-11 – Daniele D. Jul 03 '15 at 15:48
  • And you think using reflection is better than this? – Mohammad Ersan Jul 03 '15 at 15:59