Android 自定义Toast显示View

1、创建一个tosat显示的布局文件:toast_custom.xml

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<com.hjq.shape.layout.ShapeLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingVertical="@dimen/dp_20"
    android:paddingHorizontal="@dimen/dp_30"
    app:shape_radius="@dimen/dp_10"
    app:shape_solidColor="#B3000000">


    <ImageView
        android:id="@+id/toast_icon"
        android:layout_width="@dimen/dp_56"
        android:layout_height="@dimen/dp_56"
        android:src="@mipmap/toast_icon" />


    <TextView
        android:id="@+id/toast_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="保存成功"
        android:textColor="@color/white"
        android:textSize="16sp" />
</com.hjq.shape.layout.ShapeLinearLayout>

2.通过代码显示出来:

Kotlin 复制代码
  private fun showToast(text : String = "保存成功") {
        Toast(applicationContext).apply {
            duration = Toast.LENGTH_SHORT
            view = layoutInflater.inflate(R.layout.toast_custom, null)
            val tv = view?.findViewById<TextView>(R.id.toast_text)
            tv?.text = text
            show()
        }
    }

直接调用方法就行!

相关推荐
低调小一几秒前
KuiklyUI 科普:UI 如何映射到 Android View 并完成渲染
android·windows·ui
火柴就是我16 分钟前
android shadertoy效果 转换成 Android动态壁纸的写法
android
Bryce李小白1 小时前
Kotlin Flow 的使用
android·开发语言·kotlin
氦客3 小时前
Android Compose 状态的概念
android·compose·重组·状态·组合·mutablestate·mutablestateof
Jerry3 小时前
Compose 约束条件和修饰符顺序
android
千里马学框架5 小时前
安卓系统中线程优先级Priority查看方式汇总
android·framework·线程·安卓framework开发·优先级·priority
沐怡旸5 小时前
【Android】Handler/Looper机制相关的类图和流程图
android
生莫甲鲁浪戴5 小时前
Android Studio新手开发第二十一天
android·ide·android studio
生莫甲鲁浪戴5 小时前
Android Studio新手开发第二十二天
android·ide·android studio
用户41659673693555 小时前
Jetpack Compose 中实现带圆角边框的单词级富文本效果(分词与布局实践)
android