栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android 全局Toast的封装~

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android 全局Toast的封装~

APP一般Toast主要有三种,正常的、成功的、错误的。

分别为每种设计一种布局,传入提示的 text 就可以了,同时限制了相同 text 的Toast 2 秒内不能重复提示!

package com.youthmba.ymbaandroid.appbiz.basics

import android.content.Context
import android.text.TextUtils
import android.view.Gravity.CENTER
import android.view.LayoutInflater
import android.widget.TextView
import android.widget.Toast
import com.youthmba.ymbaandroid.R
import com.youthmba.ymbaandroid.appbiz.Application



public class NewToastUtils {

    companion object {
        
        var lastToastTime = 0L
        var lastToastString = ""

        @JvmStatic
        fun toastNormal(text:String?) {
            if(!TextUtils.isEmpty(text)){
                toast(text!!,R.layout.toast_normal)
            }
        }

        @JvmStatic
        fun toastSuccess(text:String?) {
            if(!TextUtils.isEmpty(text)){
                toast(text!!,R.layout.toast_success)
            }
        }

        @JvmStatic
        fun toastError(text:String?) {
            if(!TextUtils.isEmpty(text)){
                toast(text!!,R.layout.toast_error)
            }
        }

        @JvmStatic
       private fun toast(text:String,layoutId:Int) {
            if(text != lastToastString || System.currentTimeMillis() - lastToastTime > 2000L) {
                val toast = Toast(Application.getAppContext())
                toast.view = LayoutInflater.from(Application.getAppContext()).inflate(layoutId, null)
                toast.view.findViewById(R.id.tvContent).text = text
                toast.duration = Toast.LENGTH_SHORT
                toast.setGravity(CENTER, 0, 0)
                toast.show()
                lastToastTime = System.currentTimeMillis()
                lastToastString = text
            }
        }
    }

}

使用:

NewToastUtils.toastSuccess("成功了")
NewToastUtils.toastError("失败了")
NewToastUtils.toastNormal("普通提示")

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/601405.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号