Android Toast

2015/05/13

Toast

A toast is a view containing a quick little message for the user. We can also customize it! It will never receive focus. It means showing a toast will not break user’s operation.

Common methods

  • Toast.makeText(context, text, duration) - Return a toast
  • Toast.setDuration(duration) - Set duration time
  • Toast.setGravity(gravity, xOffset, yOffset) - Set position of toast
  • Toast.setText(s) - Set content of toast
  • Toast.show() - Show toast (Don’t forget!!)

Example

// Toast by default
public void ToastA(View view) {
    Toast.makeText(this, "Toast By Default", Toast.LENGTH_LONG)
            .show();
}
// Change toast's position
public void ToastB(View view) {
    Toast toast = Toast.makeText(this, "Toast Gravity", Toast.LENGTH_LONG);
    toast.setGravity(Gravity.CENTER, 0, 0);
    toast.show();
}
// Add image in toast
public void ToastC(View view) {
    Toast toast = Toast.makeText(this, "Toast Image", Toast.LENGTH_LONG);
    LinearLayout toast_layout = (LinearLayout) toast.getView();
    ImageView iv = new ImageView(this);
    iv.setImageResource(R.mipmap.ic_launcher);
    toast_layout.addView(iv);
    // toast_layout.addView(iv, 0); // Put image above toast message
    toast.show();
}
// Customize toast
public void ToastD(View view) {
    LayoutInflater i = LayoutInflater.from(this);
    Toast toast = new Toast(this);
    toast.setView(i.inflate(R.layout.toast, null));
    toast.show();
}

toast.xml for customized toast

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="30dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="This is a custom toast"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Content"/>
</LinearLayout>

Post Directory