views:

1288

answers:

1

I'm trying to set the background color of a View (in this case a Button).

I use this code:

// set the background to green
v.setBackgroundColor(0x0000FF00 );
v.invalidate();

It causes the Button to disappear from the screen. What am I doing wrong, and what is the correct way to change the background color on any View?

Thanks.

+1  A: 

and what is the correct way to change the background color on any View?

On any View? What you have is correct, though you should drop the invalidate() call.

However, some Views already have backgrounds. A Button, for example, already has a background: the face of the button itself. This background is a StateListDrawable, which you can find in android-2.1/data/res/drawable/btn_default.xml in your Android SDK installation. That, in turn, refers to a bunch of nine-patch bitmap images, available in multiple densities. You would need to clone and modify all of that to accomplish your green goals.

In short, you will be better served finding another UI pattern rather than attempting to change the background of a Button.

CommonsWare
OK, thanks for the explanation about Button backgrounds. Nine patch bitmaps (http://developer.android.com/reference/android/graphics/NinePatch.html) were new to me.I simply want to change the color of anything on the screen when I press a Button. The Buttons are on a TextView. Trying to change the color of that, leads to console messages "DDM dispatch reg wait timeout... ActivityManager: Can't dispatch DDM chunk 52454151: no handler defined" and a dialog on screen "the app stopped unexpectedly".Guess I need to do more reading on the UI. Any hints welcome. Thanks.
Peter vdL