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:

http://adilatwork.blogspot.com/2011/08/android-make-custom-view-class-based-on.html

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"?>
<selector
 xmlns:android="http://schemas.android.com/apk/res/android">
 <item
  android:state_pressed="true"
  android:drawable="@color/mypressedcolor" />
 <item
  android:state_focused="true"
  android:drawable="@drawable/myfocusedcolor" />
</selector>
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:

android:drawable="@drawable/mypresseddrawable"
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:

setBackgroundResource(R.drawable.mystatelist);
setClickable(true);
setFocusable(true);
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: