以下是使用Kotlin实现自定义Toast的示例代码:

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast

class CustomToast(private val context: Context) {

    fun show(message: String) {
        val inflater = LayoutInflater.from(context)
        val view: View = inflater.inflate(R.layout.custom_toast, null)

        val messageTextView: TextView = view.findViewById(R.id.messageTextView)
        messageTextView.text = message

        val shape = GradientDrawable()
        shape.cornerRadius = 10f
        shape.setColor(Color.parseColor("#FF4081"))
        view.background = shape

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

res目录下创建custom_toast.xml文件,用于定义自定义Toast的布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/toast_background"
    android:orientation="horizontal"
    android:padding="10dp">

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

</LinearLayout>

在使用时,可以像下面这样调用自定义Toast:

val customToast = CustomToast(this)
customToast.show("This is a custom toast message")

请注意,以上代码中的this是指当前的Activity或者Context对象。

Android 自定义 Toast - Kotlin 代码示例

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

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