首先,我们需要创建一个自定义的 Toast 布局文件,比如 '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="#80000000"
    android:padding="16dp">

    <TextView
        android:id="@+id/toast_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFFFFF"
        android:textSize="16sp" />

</LinearLayout>

然后,在你的 Activity 或者 Fragment 中,你可以使用以下代码来创建半透明的自定义 Toast:

fun showToast(context: Context, message: String) {
    val inflater = context.layoutInflater
    val layout = inflater.inflate(R.layout.custom_toast, null)

    val toastMessage = layout.findViewById<TextView>(R.id.toast_message)
    toastMessage.text = message

    val toast = Toast(context)
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0)
    toast.duration = Toast.LENGTH_SHORT
    toast.view = layout
    toast.show()
}

最后,你可以在你的代码中调用 showToast(context, message) 方法来显示半透明的自定义 Toast,其中 context 是当前的上下文,message 是你想要显示的消息。

注意:在调用 showToast() 方法之前,确保你已经设置了正确的上下文(例如,如果你在 Activity 中调用它,那么上下文应该是 this)。

Android 半透明自定义 Toast 实现 - Kotlin 代码示例

原文地址: https://www.cveoy.top/t/topic/qcB9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录