Android 自定义 Toast




前言

安卓原生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("自定义消息哦");

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值