在 Android 开发中,Toast 是一种轻量级的提示工具,用于短暂显示一条消息(通常持续 1-3 秒),无需用户交互即可自动消失。以下是详细用法和最佳实践:
一、基础用法
1. 显示简单文本
kotlin
// 在 Activity 或 Fragment 中
Toast.makeText(context, "This is a Toast", Toast.LENGTH_SHORT).show()
- 参数说明:
context
:上下文(Activity/Fragment/Application)"This is a Toast"
:提示内容(支持字符串资源R.string.message
)Toast.LENGTH_SHORT
:显示时长(可选LENGTH_LONG
,约 3.5 秒)
2. 链式调用简化
kotlin
Toast.makeText(this, "Hello Kotlin!", Toast.LENGTH_SHORT).apply { show() }
二、进阶功能
1. 自定义显示位置
调整 Toast 在屏幕上的位置:
kotlin
val toast = Toast.makeText(this, "Top Right Toast", Toast.LENGTH_LONG)
toast.setGravity(Gravity.TOP or Gravity.END, 0, 0) // 右上角,x/y 偏移量
toast.show()
2. 带图标的 Toast(仅限旧版系统)
kotlin
val toast = Toast.makeText(this, "With Icon", Toast.LENGTH_SHORT)
toast.view?.findViewById<ImageView>(android.R.id.icon)?.setImageResource(R.drawable.ic_info)
toast.show()
注意:Android 8.0(API 26)及以上系统默认隐藏图标,需自定义布局实现。
3. 自定义布局
创建自定义布局 custom_toast.xml
:
xml
<!-- res/layout/custom_toast.xml -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/toast_bg"
android:padding="16dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/iv_icon"
android:layout_width="24dp"
android:layout_height="24dp"
android:src="@drawable/ic_success" />
<TextView
android:id="@+id/tv_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:textColor="@android:color/white"
android:textSize="14sp" />
</LinearLayout>
在代码中加载:
kotlin
val inflater = layoutInflater
val layout = inflater.inflate(R.layout.custom_toast, findViewById(R.id.custom_toast_root))
val toast = Toast(applicationContext).apply {
duration = Toast.LENGTH_LONG
view = layout
setGravity(Gravity.CENTER, 0, 0)
}
layout.findViewById<TextView>(R.id.tv_message).text = "Operation Completed"
toast.show()
三、最佳实践
1. 封装工具类
避免重复代码,创建全局 Toast 工具:
kotlin
object ToastUtils {
private var toast: Toast? = null
fun show(context: Context, message: String, duration: Int = Toast.LENGTH_SHORT) {
toast?.cancel() // 避免重复显示
toast = Toast.makeText(context.applicationContext, message, duration).apply { show() }
}
}
// 使用示例
ToastUtils.show(activity, "Data saved successfully")
2. 线程安全
在后台线程显示 Toast 时需切回主线程:
kotlin
thread {
// 后台操作...
runOnUiThread {
Toast.makeText(this@MainActivity, "Background task done", Toast.LENGTH_SHORT).show()
}
}
3. 替代方案
- Snackbar:更现代的提示控件(需 Material Design 依赖),支持交互按钮:kotlin
Snackbar.make(view, "Item deleted", Snackbar.LENGTH_LONG) .setAction("Undo") { /* 撤销操作 */ } .show()
四、注意事项
上下文选择
- 优先使用
Application
上下文(避免内存泄漏):kotlinToast.makeText(applicationContext, "Message", Toast.LENGTH_SHORT).show()
- 优先使用
Android 11+ 限制
- 后台应用无法显示 Toast(需在前台显示)。
避免滥用
- 不要用 Toast 显示关键信息(用户可能忽略)。
- 频繁弹出 Toast 会干扰用户体验。
五、常见问题
1. Toast 不显示?
- 检查是否在主线程调用。
- 确认未在
onPause()
或onDestroy()
生命周期中调用。
2. 如何全局显示 Toast?
通过 Application
类扩展:
kotlin
class MyApp : Application() {
companion object {
fun showToast(message: String) {
Toast.makeText(instance, message, Toast.LENGTH_SHORT).show()
}
}
override fun onCreate() {
super.onCreate()
instance = this
}
}
// 使用示例
MyApp.showToast("Global Toast")
3. 自定义 Toast 内存泄漏?
- 避免在自定义布局中持有 Activity 引用。
- 使用
Application
上下文创建 Toast。
通过合理使用 Toast,你可以为用户提供非侵入式的友好提示。如果需要更复杂的交互式通知,建议学习 Snackbar 或 Dialog!