Wednesday, October 5, 2011

Android selector background issue for Layouts

How many times we have found that if you wish to have a background to your layout, similar to what we get in list items by using the tag its just not possible in Android.

In order to get this on a layout there is still a way.

Lets consider that we have a layout as below:

Relative Layout
Text View
Image View
Relative Layout

Now if you want to have the background of your layout from something like a drawable for both the states like pressed and default it simply doesn't take it even using the as the background.

In cases like this below technique can be used to just get the desired behaviour.

1. Create the layout file as
Relative Layout
View (Background of the layout, width and height should be same as the outer Layout)
Text View
Image View
Relative Layout

2. Go to the .java file.
Set the onTouchListener() to the RelativeLayout.
In that check for the following MotionEvents
a. MotionEvent.ACTION_DOWN
b. MotionEvent.ACTION_UP & MotionEvent.ACTION_CANCEL

3. In this if-else do the following:
a. From the View object use findViewById() and findViewById()
b. Set the background color and background resource on the view and textview.

4. "return false" from the onTouchListener() in case you want events in onClickListener().

That would give you the "" feel on a simple layout.

Note: when you are trying to set the color make sure its (0xffRRGGBB) i was trying (0xRRGGBB) and was not getting the correct color, wasted half an hour debugging this.

Signing off,
J

No comments:

Post a Comment