Saturday, October 26, 2013

Button vs ImageButton

All ImageButtons are buttons but not necessarily Buttons, and obviously not all buttons are ImageButtons. Are all TextButtons Buttons? Yes, but it's a trick question, because TextButtons don't exist, since Buttons are text buttons.

When Upper West Sliders couldn't come up with any deals (rare),  some simple text would be displayed informing the user of this sorry state. That's not really helpful, so I wanted to turn that text into a Button, which lets them search again. What's a Button? According to Google, inventor of the Android Button, a Button:

"Represents a push-button widget. Push-buttons can be pressed, or clicked, by the user to perform an action.
A typical use of a push-button in an activity would be the following:
 public class MyActivity extends Activity {
     protected void onCreate(Bundle icicle) {


         final Button button = (Button) findViewById(;
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // Perform action on click
A button looks pretty basic. Instead of just some text with a rectangular background, why not make the button look like something fun, and delicious, like a hamburger? Yes, Hindus will not like this app, but it will be a big hit in Johnson Market (a Muslim meat market, not a gay bar). To do that we need an ImageButton. Remember that dude, mkyong, I love? Let's ask him for help with an ImageButton:

In Android, you can use “android.widget.ImageButton” to display a normal “Button“, with a customized background image.
In this tutorial, we show you how to display a button with a background image named “android_button.png“, when user click on it, display a short message. As simple as that.
1. Add Image to Resources
Put image “android_button.png” into “res/drawable-?dpi” folder. So that Android know where to find your image.
2. Add ImageButton
Open “res/layout/main.xml” file, add a “ImageButton” tag, and defined the background image via “android:src“.
3. Code Code
Here’s the code, add a click listener on image button.
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class MyAndroidAppActivity extends Activity {
 ImageButton imageButton;
 public void onCreate(Bundle savedInstanceState) {
 public void addListenerOnButton() {
  imageButton = (ImageButton) findViewById(;
  imageButton.setOnClickListener(new OnClickListener() {
   public void onClick(View arg0) {
    "ImageButton is clicked!", Toast.LENGTH_SHORT).show();

4. Demo

Run the application.
1. Result, a button with a customized background image.
2. Click on the button, a short message is displayed.

No comments:

Post a Comment