在我们开发APP的过程中难免会用到toast,但是系统自带的toast无论从样式还是性能上来看都不是理想的,在这样的情况下,我们就需要自己定义toast来替代系统的toast。
首先我们需要定义一个类叫ToastUtil,代码如下:
public class ToastUtil {
private static Toast mToast;
private static Handler mHandler = new Handler();
private static Runnable runnable = new Runnable() {
public void run() {
mToast.cancel();
mToast = null;
}
};
public static void showToast(Context context, String message) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_toast, null);
TextView text = (TextView) view.findViewById(R.id.toast_message);
text.setText(message);
mHandler.removeCallbacks(runnable);
mToast = new Toast(context);
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.setView(view);
mToast.show();
}
}
通过上面的代码可以看出来其实就是利用加载布局文件的方式替换系统toast的样式,我的custom_toast.xml文件是这样的:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:background="@drawable/toast_bg"
android:padding="10dp">
<TextView
android:id="@+id/toast_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:maxLines="2"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:text=""
android:textColor="#fff"
android:textSize="14sp" />
</RelativeLayout>
toast_bg.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#7791B6" />
<corners android:radius="8dp" />
</shape>
以下是显示效果:
是不是比系统自带toast美观呢?