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

直接调用方法就行!

相关推荐
平头哥技术团队6 小时前
Day 10 | 工欲善其事:VS Code 配置与项目归档
android·开发语言·前端·javascript·html·交互
冬木家居6 小时前
40㎡客厅变形记,小家住出大自由[特殊字符]
android·经验分享·笔记·智能家居·微信公众平台
AFinalStone7 小时前
Android 7系统无障碍服务(六)输入事件拦截与 TouchExplorer
android·无障碍服务
天空之城--7 小时前
MT管理器Android逆向工程完全指南:从入门到实战
android
Anhty8 小时前
2026九月最新变声器测评:iOS安卓双端适配,低延迟运行更稳定
android·人工智能·功能测试·ios·智能手机
渡我白衣10 小时前
并查集:基础认识与模拟实现
android·java·javascript·数据结构·c++·算法·并查集
Android-Flutter12 小时前
flutter GetX 详解
android·flutter
MyFreeIT13 小时前
Android Manual
android
hai_android14 小时前
AIDL 实现 IPC 进程间通信
android·android studio
AFinalStone15 小时前
Android 7系统无障碍服务(五)AccessibilityNodeInfo 的构建与查询
android·无障碍服务