Toast play a major role to enhance user experience on android application. It’s a good practice to show user toast while the user interacts with your application. In this blog, i’m going to show you how we can create custom Toast in Android.First, create a layout (custom_toast) for a Toast here given below code we defined our linear layout with the orientation horizontal and a text view.
Like I said we are creating custom toast so we can add shape drawable, any selector drawable or even place button inside layout which would be displayed as the toast to the user and perform any event on it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<layout <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/custom_toast_layout" android:background="@color/primary_color" android:orientation="horizontal"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/toast_txt" android:padding="@dimen/padding" android:textSize="16sp" android:textAlignment="center" android:text="Toast" android:textColor="@color/white"/> </LinearLayout> </layout> |
Here my class MakeToast where we define shortToast() method in which we are initializing .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class MakeToast { private LayoutInflater inflater; private Toast toast; private CustomToastBinding toastBinding; private TextView textView; public void shortToast(Context context, final String msg) { inflater = LayoutInflater.from(context); toastBinding=CustomToastBinding.inflate(inflater); textView=toastBinding.toastTxt; textView.setText(Html.fromHtml(msg)); toast=new Toast(context); toast.setGravity(Gravity.BOTTOM,0,15); toast.setView(toastBinding.getRoot()); toast.setDuration(Toast.LENGTH_SHORT); toast.show(); } } |
To display the user your custom toast:
1 |
new MakeToast().shortToast(this,"YOUR MSG"); |
If you have any doubt comment below.