Saturday, August 30, 2014

How to create a custom toast in android

Toast messages are used display simple feedback to the user for some certain operations that happens in application. We can use toast messages to display such as Message saved to draft, Message has been sent, Record saved successfully .. etc for given time period.

First, instantiate a Toast object with one of the makeText() methods. This requires the application Context the text message, and the duration for the toast. Once it's initialized, you can display the toast notification with calling show() method.

Following example demonstrate creating a simple toast message:

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();

Or else you can directly display a toast message as follows:
Toast.makeText(context, text, duration).show();

To create a custom toast message, first create a layout for the custom view. Will create custome_toast_1.xml.
<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="8dp"
              android:background="#DAAA"
              >
    <ImageView android:src="@drawable/droid"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginRight="8dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textColor="#FFF"
              />
</LinearLayout>
Notice that the ID of the LinearLayout element is "toast_layout_root". You must use this ID to inflate the layout from the XML, as shown here:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
                               (ViewGroup) findViewById(R.id.toast_layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

No comments:

Post a Comment