一、避免连续点击后,Toast持续弹出,体验不好
public class ToastUtil { private static Context context = null; private static Toast toast = null; public static void getToast(Context context,String theText){ if (toast == null) { toast = Toast.makeText(context, theText, Toast.LENGTH_SHORT); } else { toast.setText(retId); toast.setDuration(Toast.LENGTH_SHORT); } toast.show(); } }
使用:Toast.getToast(MainActivity.this,"我的Toast");
到此就完成了
二、自定义样式的Toast
public class CustomerToast { private static Toast toast; public static void showToast(Context context, String content) { LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.toast_show, null); TextView tv = (TextView) view.findViewById(R.id.tv_toast_text); tv.setText(content); //防止多次点击按钮出现很多toast一直不消失 if (toast != null) { toast.setView(view); } else { toast = new Toast(context); toast.setView(view); toast.setDuration(Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); } toast.show(); } }
下面是布局文件toast_show
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv_toast_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@drawable/mytoastshape" android:gravity="center" android:paddingBottom="8dp" android:paddingLeft="30dp" android:paddingRight="30dp" android:paddingTop="8dp" android:textColor="#ffffff" /> </LinearLayout>
在drawable文件夹下创建Toast样式:mytoastshape
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@android:color/darker_gray" /> <corners android:radius="16dp" /> </shape >
使用:
CustomerToast.showToast(MainActivity.this, "我的Toast");
完成