Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Customizing the Appearance of a Toast

Author: Rachee Singh
Published? true -- FormatLanguage: W

Problem:

You want to customize the look of Toast notifications.

Solution:

By defining an XML layout for the toast and then inflating the view in Java, a Toast can be customized.

Discussion:

We will first define the layout of the custom Toast in an XML file, toast_layout.xml. It contains an ImageView and a TextView:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/toast_layout_root"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp"
              android:background="#f0ffef"
              >
    <ImageView android:id="@+id/image"
               android:layout_width="wrap_content"
               android:layout_height="fill_parent"
               android:layout_marginRight="10dp"
               />
   <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#000000"
              />
</LinearLayout>

Then, in the Java code, we inflate this view using LayoutInflater. We set the gravity and duration of the toast. The setGravity method modifies teh position at which the toast will be displayed. On the click of the customToast button, we show the Toast.

        customToast = (Button)findViewById(R.id.customToast);
     
        LayoutInflater inflater = getLayoutInflater();
	View layout = inflater.inflate(R.layout.toast_layout, 
            (ViewGroup) findViewById(R.id.toast_layout_root));

	ImageView image = (ImageView) layout.findViewById(R.id.image);
	image.setImageResource(R.drawable.icon);
	TextView text = (TextView) layout.findViewById(R.id.text);
	text.setText("Hello! This is a custom toast!");
	
	final Toast toast = new Toast(getApplicationContext());
	toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
	toast.setDuration(Toast.LENGTH_LONG);
	toast.setView(layout);
	customToast.setOnClickListener(new View.OnClickListener() {
		@Override
			public void onClick(View arg0) {
	        toast.show();
	    }
	});
        

Download:

The source code for this project can be downloaded from https://docs.google.com/leaf?id=0B_rESQKgad5LYTFjYjY4NWEtM2YzZC00NzEzLTg5ZGEtMzFhM2UxOWM2MmFk&hl=en_US.

Download:

The source code for this project is in the Android Cookbook repository at http://github.com/IanDarwin/Android-Cookbook-Examples, in the subdirectory CustomToast.
No records found.