Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to use Image Buttons and Toast in Android

In this article we’ll see you how to use image buttons and how to use toast and create custom toasts in your application.

Image Buttons and Toast

Now toast has nothing to do with toasted bread, it is in fact a popup. It’s a popup of information. For example if you click on a button it may tell you an operation has occurred. A good example of a toast would be when you’re on Xbox live and a message pops up telling you your friend is online. See http://developer.android.com/guide/topics/ui/notifiers/toasts.html for an explanation from the Android Developers site.

Image Buttons and Toast

Figure 1: Image Buttons and Toast

The Application

Ok for this tutorial I will create 5 image buttons. 4 will change the background of the screen and also pop up a toast and the remaining image button will exit the application. Without further ado, let’s start the project.

Open Eclipse and create a new Project. Name it Application2. Name your main Activity Application2Activity.

Project Structure

Figure 2: Project Structure

Notice I have placed several images into the drawablw_hdpi folder. For this tutorial you will have to obtain 09 images. You will need an empty room image, 4 different living room images, an exit sign image and also an image of the number two, three and four. The ic_launcher image will already be in that folder when the project is created. Save the images as .png and put them in drawable-hdpi folder. Note for beginners: If you have trouble finding your folders to save the images, an easy way to put the images in that folder is to copy them from where you have saved then right click on the drawable-hdpi folder in the Eclipse folder structure as seen above and select paste. Right we are ready to get coding.

Step 1:

Copy and paste this code into you main activity: (Remember not to copy over your project name at the top of your main activity)

Listing 1: Main Activity

import android.R.color;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Application2Activity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final ImageButton Btn_living_room1 = (ImageButton) findViewById(R.id.Btn_living_room1);
                
        Btn_living_room1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
            	
            	v = findViewById(R.id.laidout);
                v.setBackgroundResource(R.drawable.living_room1);
                Toast toast = Toast.makeText(getApplicationContext(), "Living Room 1 Selected", Toast.LENGTH_SHORT);
                toast.show();
                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                             
            }
        });
        
        final ImageButton Btn_living_room2 = (ImageButton) findViewById(R.id.Btn_living_room2);
                
        Btn_living_room2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
            	
            	v = findViewById(R.id.laidout);
                v.setBackgroundResource(R.drawable.living_room2);
                
                //get your custom_toast.xml layout
				LayoutInflater inflater = getLayoutInflater();
 
				View layout = inflater.inflate(R.layout.custom_toast,
				  (ViewGroup) findViewById(R.id.custom_toast_layout_id));
 
				// set a dummy image
				ImageView image = (ImageView) layout.findViewById(R.id.image);
				image.setImageResource(R.drawable.two);
 
				// set a message
				TextView text = (TextView) layout.findViewById(R.id.text);
				text.setText("Living Room 2 Selected");
 
				// Toast...
				Toast toast = new Toast(getApplicationContext());
				toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
				toast.setDuration(Toast.LENGTH_SHORT);
				toast.setView(layout);
				toast.show();
                                
            }
        });
        
        final ImageButton Btn_living_room3 = (ImageButton) findViewById(R.id.Btn_living_room3);
                
        Btn_living_room3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
            	
            	v = findViewById(R.id.laidout);
                v.setBackgroundResource(R.drawable.living_room3);
                
              //get your custom_toast.xml layout
				LayoutInflater inflater = getLayoutInflater();
 
				View layout = inflater.inflate(R.layout.custom_toast,
				  (ViewGroup) findViewById(R.id.custom_toast_layout_id));
 
				// set a dummy image
				ImageView image = (ImageView) layout.findViewById(R.id.image);
				image.setImageResource(R.drawable.three);
 
				// set a message
				TextView text = (TextView) layout.findViewById(R.id.text);
				text.setText("Living Room 3 Selected");
 
				// Toast...
				Toast toast = new Toast(getApplicationContext());
				toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
				toast.setDuration(Toast.LENGTH_SHORT);
				toast.setView(layout);
				toast.show();
				
            }
        });
        
        final ImageButton Btn_living_room4 = (ImageButton) findViewById(R.id.Btn_living_room4);
               
        Btn_living_room4.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
            	
            	v = findViewById(R.id.laidout);
                v.setBackgroundResource(R.drawable.living_room4);
                
              //get your custom_toast.xml layout
				LayoutInflater inflater = getLayoutInflater();
 
				View layout = inflater.inflate(R.layout.custom_toast,
				  (ViewGroup) findViewById(R.id.custom_toast_layout_id));
 
				// set a dummy image
				ImageView image = (ImageView) layout.findViewById(R.id.image);
				image.setImageResource(R.drawable.four);
 
				// set a message
				TextView text = (TextView) layout.findViewById(R.id.text);
				text.setText("Living Room 4 Selected");
 
				// Toast...
				Toast toast = new Toast(getApplicationContext());
				toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
				toast.setDuration(Toast.LENGTH_SHORT);
				toast.setView(layout);
				toast.show();
            }
        });
        
        final ImageButton Btn_exit2 = (ImageButton) findViewById(R.id.Btn_exit2);
        Btn_exit2.setBackgroundColor(color.transparent);

        Btn_exit2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
            	
            	finish();
            }
        });
    }
}

Step 2:

Copy and paste this code into your main.xml file:

Listing 2: main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/laidout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/empty_room"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:gravity="center"
        android:text="@string/heading"
        android:textColor="#FFFFFF"
        android:textSize="24sp" />

    <ImageButton
        android:id="@+id/Btn_exit2"
        android:layout_width="135dp"
        android:layout_height="55dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="40dp"
        android:src="@drawable/exit2" />

    <ImageButton
        android:id="@+id/Btn_living_room3"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_above="@+id/Btn_exit2"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="35dp"
        android:layout_marginLeft="25dp"
        android:src="@drawable/living_room3" />

    <ImageButton
        android:id="@+id/Btn_living_room1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignLeft="@+id/Btn_living_room3"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="62dp"
        android:src="@drawable/living_room1" />

    <ImageButton
        android:id="@+id/Btn_living_room4"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/Btn_living_room3"
        android:layout_marginRight="26dp"
        android:src="@drawable/living_room4" />

    <ImageButton
        android:id="@+id/Btn_living_room2"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignLeft="@+id/Btn_living_room4"
        android:layout_alignTop="@+id/Btn_living_room1"
        android:src="@drawable/living_room2" />

</RelativeLayout>

Step 3:

Copy and paste this code into your string.xml file (into the values folder which is in the res folder):

Listing 3: string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="heading"><u><b>ImageButtons</b></u></string>
    <string name="app_name">Application2</string>

</resources>

Step 4:

Right click on the layout folder and select New then File and name it custom_toast.xml. Copy and paste this code into your custom_toast.xml file:

Listing 4: custom_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toast_layout_id"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#4672AA"
    android:orientation="horizontal"
    android:padding="5dp" >
 
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="5dp" />
 
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#000" />
 
</LinearLayout>

Now that you have all the code entered and there are no errors, we are ready to roll. Run the application and you should get something like this:

Application running.

Figure 3: Application running.

ImageButton Btn_living_room1 clicked and toast displayed.

Figure 4: ImageButton Btn_living_room1 clicked and toast displayed.

ImageButton Btn_living_room2 clicked and custom toast is displayed.

Figure 5: ImageButton Btn_living_room2 clicked and custom toast is displayed.

ImageButton Btn_living_room3 clicked and custom toast is displayed.

Figure 6: ImageButton Btn_living_room3 clicked and custom toast is displayed.

ImageButton Btn_living_room4 clicked and custom toast is displayed.

Figure 7: ImageButton Btn_living_room4 clicked and custom toast is displayed.

Code Breakdown

Firstly we’ll look at some of the code in the main.xml file. We used a Relative layout. Best to mess around with this in the GUI interface but it’s useful to go into the code if the components become difficult to manage onscreen, i.e. too many components on screen or they won’t go where you want them to. There are several layouts you can use but for this article I thought it would be a nice touch to introduce a new one to you.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/laidout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/empty_room"
    android:orientation="vertical" >

Notice we give it an id so we can change the background later and also notice I use an empty room image as a background.

<ImageButton
        android:id="@+id/Btn_living_room3"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_above="@+id/Btn_exit2"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="35dp"
        android:layout_marginLeft="25dp"
        android:src="@drawable/living_room3" />

Notice this ImageButton android:layout_above="@+id/Btn_exit2"etc. With relative layout components positions are relative to other components. Also notice android:src="@drawable/living_room3". This assigns our image button with the desired image.

The custom_toast.xml basically defines what your custom toast will look like. This can be used for multiple toasts.

Listing 5: custom_toast.xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toast_layout_id"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#4672AA"
    android:orientation="horizontal"
    android:padding="5dp" >
 
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="5dp" />
 
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#000" />
 
</LinearLayout>

Here I gave it a blue background: android:background="#4672AA"

Now for our main activity. Take notice of the imports:

Listing 6: Imports

import android.R.color;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

Listing 7: Declaring the ImageButtons and giving them actions to perform

//Declaration:
final ImageButton Btn_living_room1 = (ImageButton) findViewById(R.id.Btn_living_room1);
                
        Btn_living_room1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
            	
//Using id of main.xml: v = findViewById(R.id.laidout);
//Setting our background view to living_room1: imagev.setBackgroundResource(R.drawable.living_room1);

//Using toast:
                Toast toast = Toast.makeText(getApplicationContext(), "Living Room 1 Selected", Toast.LENGTH_SHORT);
                toast.show();
//Setting position:   toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                             
            }
        });

Listing 8: Implementing the custom toast

final ImageButton Btn_living_room3 = (ImageButton) findViewById(R.id.Btn_living_room3);
                
        Btn_living_room3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
            	
            	v = findViewById(R.id.laidout);
v.setBackgroundResource(R.drawable.living_room3);
                
              //get your custom_toast.xml layout
				LayoutInflater inflater = getLayoutInflater();
 
				View layout = inflater.inflate(R.layout.custom_toast,
				  (ViewGroup) findViewById(R.id.custom_toast_layout_id));
 //Notice reference to dummy image in our custom_toast.xml:               
				// set a dummy image
				ImageView image = (ImageView) layout.findViewById(R.id.image);

//We place our three image in our custom toast:				image.setImageResource(R.drawable.three);
 
				// set a message
				TextView text = (TextView) layout.findViewById(R.id.text);
				text.setText("Living Room 3 Selected");
 
				// Toast...
				Toast toast = new Toast(getApplicationContext());
				toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
				toast.setDuration(Toast.LENGTH_SHORT);
				toast.setView(layout);
				toast.show();
				
            }
        });

In this application I use custom_toast.xml file for 3 different toasts. Finally we use an Exit ImageButton to exit the application. Use finish(); to exit the application as seen below:

Listing 9: Creating an Exit ImageButton to exit the application

final ImageButton Btn_exit2 = (ImageButton) findViewById(R.id.Btn_exit2);
        Btn_exit2.setBackgroundColor(color.transparent);

        Btn_exit2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
            	
            	finish();
            }
        });

Conclusion

From this article you should now be familiar with the use of image buttons, toast messages, creating custom toasts and using a relative layout. I hope this article has been useful to you. If you enjoyed it or got any help at all from it just give me a like. Thanks for reading. Catch you next time.

Steve



Has designed and developed several android applications from scratch which are available on Google Play.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login