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()
        }
    }

直接调用方法就行!

相关推荐
m0_748233646 分钟前
RabbitMQ 进阶
android·前端·后端
Mr.pyZhang4 小时前
Android构建系统 - 04 编译产物
android·linux
守城小轩10 小时前
Brave 132 编译指南 Android 篇 - 编译准备:系统要求与推荐工具 (三)
android·chrome·chrome devtools·指纹浏览器·浏览器开发·brave
m0_7482384210 小时前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
程序员江同学11 小时前
Kotlin 技术月报 | 2025 年 2 月
android·kotlin
甜于酸13 小时前
MuMu模拟器Pro for Mac 安卓手机平板模拟器
android·macos·智能手机
顾林海15 小时前
深入解析 Android Activity 生命周期
android
XuanRanDev17 小时前
【构建工具】Gradle Kotlin DSL中的大小写陷阱:BuildConfigField
android·开发语言·kotlin
Nathan2024061620 小时前
Room - 基本使用及使用问题
android·面试·android jetpack
攻城狮_Dream21 小时前
基于 Python 的项目管理系统开发
android·数据库·python