Android Tutorial #4.1: Image & Text-Only Buttons (UPDATED)

This very simple tutorial will add to your Android UI (user interface) development arsenal. How? Buttons that display as simple text or as images are basic elements of any application. By following the two steps below, these buttons can be easily created with Google’s Android by simply extending the current Button and ImageButton classes.

We will create these two new Button extensions as shown:

Text and Image Buttons

Step 1: Set Background to ‘null’ in XML or code

The recommended technique is to use the ‘empty’ drawable variable in your ImageButton or TextButton’s XML to set your background to null:

android:background=”@android:drawable/empty”

An optional technique is to extend ImageButton or TextButton and to set the background to null in the constuctor. As above, this is not the recommended approach but may be useful at times:

public YourButtonExtension() {

setBackground(null);

}

And that’s it, only your image or text will display but will have button functionality…except for visually displaying focus. Let’s address that next.

Step 2: Handle onFocus() by overriding onDraw()

We listen for the focus event and update the Button’s text color or button image that way as well. But we’ll do it this way for now.

public void onDraw(Canvas canvas) {

// Since this Button now has no background. We must set the text color to indicate focus.
if (isFocused()) {

// Set the focused text color. In the case of ImageOnlyButton we would .
// instead do setImageResource(imageResourceFocused);
setTextColor(focusedTextColor);

} else {

// Set the non-focused text color. In the case of ImageOnlyButton we would .
// instead do setImageResource(imageResourceNotFocused);
setTextColor(notFocusedTextColor);

}

super.onDraw(canvas);

}

You might be wondering where those text color and image variables come from. We will obtain these focused & not-focused images or text colors from variables passed in from the XML resource file as you’ll see by reading the source code. I won’t go into how that happens here. Instead, I’ll keep this tutorial simple and point you to my next tutorial where I will discuss how to create & pass such custom variables.

And That’s It

You can download the source to see for yourself.