Custom Toast

16:09:00 0 Comments A + a -


Certainly, toasts were boring and I'm sure you have resorted to a better message library but you could now use custom views to display toasts.

So, now you can dress up your toast to show some simple app messages/notifications. You could also have an image in them. If you would have to add a custom toast layout to a toast to show a message, you would have to do the following.

Create the custom layout for your toast.

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <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="@color/dark_red">
        <ImageView android:src="@drawable/ic_battery_alert"
                   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>
</LinearLayout>
You could set text and other attributes to your toast like this,
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); 
// Use string resource
text.setText("Out of battery! Plugin to a charger immediately. "); 
 // Positioning the toast: gravity, xOffset, yOffset
toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM, 0, 50);
// Duration of toast
toast.setDuration(Toast.LENGTH_LONG); 
// Custom toast layout
toast.setView(layout); 
toast.show();












Android Developer, Tech Enthusiast, Startup Aficionado, Seeker of Happiness.