Here is my solution with a custom toast handler. Works great in m application.
public class CustomToast { private LayoutInflater inflater; private Toast toast; private View customToastLayout; private TextView LblCustomToast; public CustomToast() {} public void showCustomToast(String toastMessage, int toastLength, AppCompatActivity context) { if(inflater == null) {inflater = context.getLayoutInflater();} if(customToastLayout == null) {customToastLayout = inflater.inflate(R.layout.toast_layout, (ViewGroup) context.findViewById(R.id.toast_layout_root));} if(LblCustomToast == null) {LblCustomToast = (TextView) customToastLayout.findViewById(R.id.LblCustomToast);} LblCustomToast.setText(toastMessage); if(toast == null) {toast = new Toast(context);} toast.setGravity(Gravity.CENTER_VERTICAL| Gravity.BOTTOM, 0, DPDensity.getPxFromDP(160, context.getResources())); toast.setDuration(toastLength); toast.setView(customToastLayout); if(toast.getView().isShown()) {toast.cancel();}
Here is the XML layout
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_layout_root" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="15dp" android:paddingTop="5dp" android:paddingRight="15dp" android:paddingBottom="5dp" android:orientation="vertical" android:background="@drawable/custom_toast_bg" android:gravity="bottom|center" android:layout_marginBottom="50dp"> <TextView android:id="@+id/LblCustomToast" android:text="Test" android:textSize="16dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/lightLime" android:layout_gravity="center" android:gravity="center"/> </LinearLayout>
And here is the use:
customToast = new CustomToast(); customToast.showCustomToast(getString(R.string.your_message), Toast.LENGTH_SHORT, (AppCompatActivity) mainActivityContext);
source share