Wednesday, November 9, 2011

Showing different Drawables for different ImageButton states (Outside box version)

This blog entry will show you how to show different Drawable when state of ImageButton changed.


First of all I prepared three different PNG files below



android.png : The green Android for showing when no action on the button



android_focus.png: The blue Android for showing when user selected the button



android_pressed.png: The red Android for showing when user pressed on the button

In my Activity after I initialized ImageButton object then set OnTouchListener and OnFocusChangeListener and let the button showing each image based on each state like this


// initiate ImageButton
ImageButton btn = (ImageButton) findViewById(R.id.imgbtn);
btn.setImageResource(R.drawable.android);

// set OnFocusChangeListener
btn.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
ImageButton btn = (ImageButton) v;
if(hasFocus){
// has focus, showing blue android
btn.setImageResource(R.drawable.android_focus);
}else{
// loose focus, showing green android again
btn.setImageResource(R.drawable.android);
}
}
});

// set OnTouchListener

btn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
ImageButton btn = (ImageButton) v;

if(event.getAction()==MotionEvent.ACTION_DOWN){
//User pressed button, showing red android
btn.setImageResource(R.drawable.android_pressed);
}else if(event.getAction() == MotionEvent.ACTION_UP){
//User released button, showing green android again
btn.setImageResource(R.drawable.android);
}

return false;
}
});


By applying the code above in runtime the button will showing green Android when has no action, showing blue Android when user selected the button and showing red Android when user pressed the button.

But in the real world this method isn't famous; it needs to implement several Interfaces to done this job. Normally in Android UI development if you want to show different images when button state changed like this example the famous way to do is by declare the image files to show for each button states in the XML file. You can see the instruction in Android Developer website.

This method is good when you want to show the image that create at runtime. For example, if you want to use external Android SVG library to convert SVG file into Drawable objects and display each Drawable in different ImageButton states. In this case the SVG files are encoded to Drawable objects in runtime, and you cannot use XML file to reference to it, so this method can help you to achieve the goal.