Thursday, 27 October 2011

Android: changing background color or drawable of a custom View when it's pressed or focused

Let's say you've created your own custom view named MyCustomView which extends the FrameLayout class and you've added to it your own xml layout (as defined in layout/mycustomview.xml), something like the following post:

Now you want MyCustomView to change its background color or drawable when it's pressed or focused. The first thing you'll need to do is define a State List resource. This is done by creating an xml file in the res/drawable folder (let's called it res/drawable/mystatelist.xml) which has contents something like the following:

<?xml version="1.0" encoding="utf-8"?>
  android:drawable="@color/mypressedcolor" />
  android:drawable="@drawable/myfocusedcolor" />
We'll assume mypressedcolor and myfocusedcolor are colors defined in the res/values folder. The values of android:drawable of course needn't necessarily be a color but can alternatively be a drawable with value something like the following:

Next, somewhere in MyCustomView we need to set its background resource to be the State List resource we just defined, and to also set MyCustomView to be focusable and clickable, as follows:

Note that you're setting the properties (background resource, is focusable, is clickable) of MyCustomView itself and not the properties of the outermost node in the mycustomview.xml layout file which is added to MyCustomView (like I did mistakenly!).

That's it. You've defined a custom view and now it changes its background color or drawable when it is pressed or focused.

No comments: