In this post we will be talking about the most helpful feature provided by Android for a quick notification to user, i.e. Toasts “Small informative texts shown at bottom-center of device screen, for defined time duration”.
Default UI design of these toasts is a semi-transparent dark color background with white text over it, not even showing the name of application which spawned it, no so eye-catching, right? I know… So, let’s make a custom Toast Notification that complements our awesome UI…
“layout_toast.xml”
<?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:background="@drawable/shape_toast" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_launcher" android:gravity="center_vertical" android:text="@string/app_name" android:textColor="@android:color/black" /> <TextView android:id="@+id/toast_message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" /> </LinearLayout>
“shape_toast.xml”
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <corners android:radius="4dp" /> <padding android:bottom="10dp" android:left="10dp" android:right="10dp" /> <solid android:color="@android:color/white" /> <stroke android:dashGap="2dp" android:dashWidth="2dp" android:width="2dp" android:color="@android:color/black" /> </shape>
“MainActivity.java”
View toastView = getLayoutInflater().inflate(R.layout.layout_toast, null); TextView textMessage = (TextView) toastView.findViewById(R.id.toast_message); textMessage.setText(toastMessage); Toast customToast = new Toast(getApplicationContext()); customToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 10, 10); customToast.setDuration(Toast.LENGTH_LONG); customToast.setView(toastView); customToast.show();
As shown here, you just need to inflate the view you want to show in toast, create an instance of Toast class, and set the inflated view in this instance. That’s all, now just customize the gravity and duration of toast instance and show it.
For a quick example, you can check this link for source code and .apk file. (link: http://rapidshare.com/share/6BC3620195C5B7067F0FDC46424EEBCB)
Written By: Ankit Bansal, Android Developer, Mindfire Solutions
Reblogged this on Androider and commented:
This posts helps out to make a custom Toast Notification