Android 自定义Toast
Toast
的基础用法
Toast toast = Toast.makeText(getApplicationContext(), "Normarl toast", Toast.LENGTH_SHORT).show();
Toast
显示的位置
通常情况下Toast
显示在整个界面的底部水平中间的位置,但是Toast
现实的位置也是可以调整的,通过setGravity(int, int, int)
方法来调整其位置
Toast toast = Toast.makeText(getApplicationContext(), "Normarl toast", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, 0);
toast.show();

top_right.png
自定义Toast
创建自定义的layout文件,使用LayoutInflater
渲染布局文件,最后使用Toast
的setView(View)
方法来实现
如果不是自定义
Toast
,请使用makeText(Context, int, int)
方法来创建Toast
,不要使用Toast
的构造方法
自定义布局文件res/layout/custom_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_container"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="8dp"
android:background="#DAAA"
>
<ImageView android:src="@drawable/ic_action_discover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:text="This is a custom toast"/>
</LinearLayout>
Java 代码逻辑
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.custom_toast, null);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(view);
toast.show();

center.png
- 点击一次显示一次Toast
有时候连续点击会出现很多的Toast
的提示,如果用户无操作,会导致toast提示一直存在,需要等很长时间
才会消失,想要的效果是点击一次显示一次,
根据自己的需求开发不同类型的private Toast mToast; private void showToast(String msg){ if(mToast != null) mToast.cancel(); mToast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT); mToast.show(); }
Toast
分类:
android提高篇
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!