复制以下文件可直接使用:
public class ToastUtil {
/**
* show short toast
*
* @param msg
*/
public static void showShortToast(String msg) {
Toast.makeText(MyApplication.getInstance(), msg, Toast.LENGTH_SHORT).show();
}
/**
* show long toast
*
* @param msg
*/
public static void showLongToast(String msg) {
Toast.makeText(MyApplication.getInstance(), msg, Toast.LENGTH_LONG).show();
}
/**
* 居中显示 short toast
*
* @param msg
*/
public static void showCenterShortToast(String msg) {
Toast toast = Toast.makeText(MyApplication.getInstance(), msg, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
/**
* 居中显示 long toast
*
* @param msg
*/
public static void showCenterLongToast(String msg) {
Toast toast = Toast.makeText(MyApplication.getInstance(), msg, Toast.LENGTH_LONG);
//Gravity.CENTER Gravity.LEFT Gravity.RIGHT Gravity.TOP
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
/**
* 自定义toast布局,并居中显示
*
* @param msg
*/
public static void showCustomShortToast(String msg) {
View view = LayoutInflater.from(MyApplication.getInstance()).inflate(R.layout.toast_layout, null);
TextView textView = view.findViewById(R.id.id_content);
textView.setText(msg);
Toast toast = new Toast(MyApplication.getInstance());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setView(view);
toast.show();
}
/**
* 自定义toast 显示的时长
*
* @param msg
*/
public static void showCustomTimeShortToast(String msg, int time) {
final Toast toast = Toast.makeText(MyApplication.getInstance(), msg, Toast.LENGTH_LONG);
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
toast.show();
}
}, 0, 3500);//0秒后执行,LENGTH_LONG时间为3.5s,所以设置3500毫秒后再次执行
new Timer().schedule(new TimerTask() {
@Override
public void run() {
toast.cancel();
timer.cancel();
}
}, time);//time时间后执行取消taost,取消timer.
}
}
ToastUtil文件中使用到的MyApplication文件如下:
public class MyApplication extends Application {
public static MyApplication instance;
public static MyApplication getInstance() {
return instance;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
自定义Toast布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<LinearLayout
android:layout_width="200dp"
android:layout_height="110dp"
android:orientation="vertical"
android:background="#b0000000"
>
<TextView
android:layout_width="40dp"
android:layout_height="40dp"
android:background="@mipmap/icon_success"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
/>
<TextView
android:id="@+id/id_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#fff"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
效果如下:
(录屏工具推荐:GifCam 下载地址:http://www.bahraniapps.com/apps/gifcam/gifcam.php)