0

How to set the background color of an ImageButton 'transparent' ?

The following piece of code works when I try it with default android theme, but with 'Theme.Light', I see a gray background.

ImageButton deleteBtn = new ImageButton( this );
deleteBtn.setImageResource( R.drawable.delete_big );
deleteBtn.setBackgroundColor(android.R.color.transparent);

(I need to dynamically create these buttons.. I have seen solutions which mention specifying @null background color using android's layout.xml files. How can I achieve the same thing programmatically ? Any help highly appreciated. Thanks!

image with gray background here:

Community
  • 1
  • 1
Ajay
  • 977
  • 2
  • 11
  • 23
  • http://stackoverflow.com/questions/5174835/android-imagebutton-gets-gray-background/5891856#5891856 -- worked quite well for me. – Ajay Aug 21 '11 at 16:47

2 Answers2

1

I had to do something similar to this and I used a transparent png 9patch. Then you can set it to the background with something like:

deleteBtn.setBackgroundResource(R.drawable.transparent_bground);

Edit: here is a 9 patch you can use. Save it in one of your res/drawable folders.

FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
0

Even though this is kind of answered, here's what went wrong.

Watch out for colors. android.R.color.transparent actually is an integer referencing a lookup table, and every time you set a color in Android in Java, it takes in an integer that represents the color.

Now, this is the tricky part: What's happening here is that it's setting the bg color to the lookup table index, which happens to translate to gray. If I remember right, getResources().getColor(id) is a function that can be called from a context or activity to get your correct color.

Baz
  • 36,440
  • 11
  • 68
  • 94
Joe-P
  • 1