Android自定义Toast
Android自定义Toast
Android原生的Toast,看起来灰色的不太好看,我们可以通过下面的自定义Toast的方法来实现自定义Toast的布局和内容
运行结果预览图
实现步骤
1.新建 Toast背景 bg_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="#FFEB3B"/>
<corners
android:radius="25dp"/>
<padding
android:left="50dp"
android:right="50dp"
android:top="10dp"
android:bottom="10dp"/>
</shape>
2.新建Toast的布局文件 view_toast_custom.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:background="@drawable/bg_toast"
android:gravity="center"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:id="@+id/tvToast"
android:text="Toast"
android:textSize="35dp"
android:textColor="#fff"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
注:这个是Toast里面的内容,也可以加入图片,增加Toast的美观性
3.在MainActivity里面写一个函数,通过调用实现自定义Toast
public void MyToast(String str, int showTime) {
View view= LayoutInflater.from(this).inflate(R.layout.view_toast_custom,null);
TextView tv_msg = (TextView) view.findViewById(R.id.tvToast);
tv_msg.setText(str);
Toast toast = new Toast(this);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 20);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(view);
toast.show();
}
点击下载源码:下载
github下载地址:https://github.com/ldy731729142/ToastDemo
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~