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渲染布局文件,最后使用ToastsetView(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
    posted @   brave-sailor  阅读(301)  评论(0编辑  收藏  举报
    编辑推荐:
    · 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代理技术深度解析与实战指南
    · 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
    点击右上角即可分享
    微信分享提示