自定义轻提示
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
import android.content.Context
|
||||
import android.view.Gravity
|
||||
import android.view.LayoutInflater
|
||||
import android.widget.ImageView
|
||||
import android.widget.TextView
|
||||
import android.widget.Toast
|
||||
import com.example.defenseapplication.R
|
||||
|
||||
object ToastUtils {
|
||||
|
||||
private var currentToast: Toast? = null
|
||||
|
||||
/**
|
||||
* 显示成功提示
|
||||
* @param message 提示文字
|
||||
* @param duration 时长 默认Toast.LENGTH_SHORT
|
||||
*/
|
||||
fun showSuccess(context: Context, message: String, duration: Int = Toast.LENGTH_SHORT) {
|
||||
showCustomToast(context, message, true, duration)
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示失败提示
|
||||
* @param message 提示文字
|
||||
* @param duration 时长 默认Toast.LENGTH_SHORT
|
||||
*/
|
||||
fun showError(context: Context, message: String, duration: Int = Toast.LENGTH_SHORT) {
|
||||
showCustomToast(context, message, false, duration)
|
||||
}
|
||||
|
||||
private fun showCustomToast(context: Context, message: String, isSuccess: Boolean, duration: Int) {
|
||||
// 先取消上一个Toast,避免重复弹出
|
||||
currentToast?.cancel()
|
||||
|
||||
// 加载自定义布局
|
||||
val view = LayoutInflater.from(context).inflate(R.layout.layout_custom_toast, null)
|
||||
val ivIcon = view.findViewById<ImageView>(R.id.iv_icon)
|
||||
val tvMessage = view.findViewById<TextView>(R.id.tv_message)
|
||||
|
||||
// 设置图标和文字
|
||||
if (isSuccess) {
|
||||
ivIcon.setImageResource(R.drawable.fill) // 成功图标
|
||||
} else {
|
||||
ivIcon.setImageResource(R.drawable.error_circle) // 失败图标
|
||||
}
|
||||
tvMessage.text = message
|
||||
|
||||
// 创建Toast
|
||||
val toast = Toast(context.applicationContext).apply {
|
||||
setGravity(Gravity.CENTER, 0, 0) // 居中显示,和你图里一致
|
||||
this.duration = duration
|
||||
this.view = view
|
||||
}
|
||||
|
||||
// 保存当前Toast并显示
|
||||
currentToast = toast
|
||||
toast.show()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user