前言
安卓原生Toast只提供了两种展示方式 即
Toast.LENGTH_LONG 或者Toast.LENGTH_SHORT ,但这远远满足不了产品经理的各种需求,
所以本文展示的就是一个可自定义位置及时间长短的Toast ,
二、使用步骤
1.自定义布局
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg_toast"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/tvToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="要展示的吐司"
android:textColor="#fff"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
2.自定义工具类
/**
* 消息提示工具类
*
* @author summer
*/
public class ToastUtils {
/**
* 定时器
* @param toast
* @param duration
*/
public static void controlToastTime(final Toast toast, int duration) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
toast.cancel();
}
}, duration);
}
/**
* 自定义消息弹出位置
* @param s
*/
public static void show(String s) {
View view = LayoutInflater.from(App.getContext()).inflate(R.layout.view_toast_custom, null);
TextView tv_msg = (TextView) view.findViewById(R.id.tvToast);
tv_msg.setText(s);
Toast toast = Toast.makeText(App.getContext(), s, Toast.LENGTH_LONG);
controlToastTime(toast, 500);//显示时长,
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setView(view);
toast.show();
}
}
3 使用
ToastUtils.show("自定义消息哦");