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

直接调用方法就行!

相关推荐
赏金术士8 小时前
Kotlin Flow 完全指南
android·开发语言·kotlin
eric*16889 小时前
彻底解决 INSTALL_FAILED_TEST_ONLY 安装失败的问题
android·android studio·install_failed_·error code·ailed_test_only·test_only·install_failed
jushi89999 小时前
哔哩哔哩第三方安卓电视TV/车机软件 BV 简洁好用 支持低版本安卓5.0+
android
summerkissyou19879 小时前
Android-布局-属性顺序
android
xuankuxiaoyao9 小时前
Vue.js 插槽、作用域插槽、商品、阶段案例
android·vue.js·flutter
恋猫de小郭9 小时前
终于,Flutter 修复 Android 中文字体异常,但是很草台,不知怎么吐槽
android·前端·flutter
亚空间仓鼠9 小时前
Docker容器化高可用架构部署方案(八)
android·docker·架构
恋猫de小郭10 小时前
2026 Android I/O ,全新 AI 手机、 Android PC 和自动驾驶
android·人工智能·智能手机
三产10 小时前
Hermes 教程 03:Skills 系统
android·java·数据库
AI玫瑰助手10 小时前
Python流程控制:for循环遍历字符串列表字典
android·java·python