【Android开发点滴】自定义Toast样式

在我们开发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();
            //toast隐藏后,将其置为null
            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);
        //设置toast显示时长
        mToast.setDuration(Toast.LENGTH_SHORT);
        //设置Toast居中显示
//        mToast.setGravity(Gravity.CENTER, 0, 0);
        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" />
    <!-- 边框的颜色及粗细 -->
    <!--<stroke android:color="#000"-->
    <!--android:width="1px"/>-->
</shape>
以下是显示效果:

这里写图片描述

是不是比系统自带toast美观呢?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值