【问题标题】:Custom toast on Android: a simple exampleAndroid上的自定义吐司:一个简单的例子
【发布时间】:2026-01-12 22:00:01
【问题描述】:

我是 Android 编程新手。什么是在 Android 上显示自定义 toast 通知的简单示例?

【问题讨论】:

  • 自定义吐司是什么意思?你想展示什么?
  • 这不是真正的问题。您应该尝试阅读developer.android 的文档
  • 我有一个自定义消息框。如果您可以自定义它并为其添加计时器并更改其外观,我会为您发布。可以吗?
  • 这里您可以找到“自定义吐司”*.com/questions/3500197/…的基本示例

标签: android toast


【解决方案1】:

第 1 步:

首先在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_layout_id"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFF"
    android:orientation="horizontal"
    android:padding="5dp" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#000" />

</LinearLayout>

第 2 步: 在 Activity 代码中,获取上述自定义视图并附加到 Toast:

// Get your custom_toast.xml ayout
LayoutInflater inflater = getLayoutInflater();

View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_layout_id));

// set a message
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Button is clicked!");

// Toast...
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

如需更多帮助,请查看我们如何在 Android 中创建自定义 Toast:

http://developer.android.com/guide/topics/ui/notifiers/toasts.html

【讨论】:

    【解决方案2】:

    使用下面的自定义 Toast 代码。它可能会帮助你。

    toast.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/toast_layout_root"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="10dp"
        android:background="#DAAA" >
    
        <ImageView android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginRight="10dp" />
    
        <TextView android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:textColor="#FFF" />
    
    </LinearLayout>
    

    MainActivity.java

    LayoutInflater inflater = getLayoutInflater();
    View layout = inflater.inflate(R.layout.toast_layout,
                                   (ViewGroup) findViewById(R.id.toast_layout_root));
    
    ImageView image = (ImageView) layout.findViewById(R.id.image);
    image.setImageResource(R.drawable.android);
    TextView text = (TextView) layout.findViewById(R.id.text);
    text.setText("Hello! This is a custom toast!");
    
    Toast toast = new Toast(getApplicationContext());
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(layout);
    toast.show();
    

    并查看以下链接以获取自定义 Toast。

    Custom Toast with Analog Clock

    YouTube: Creating Custom Toast With Button in Android Studio

    【讨论】:

    • "(ViewGroup) findViewById(R.id.toast_layout_root)" 可以替换为“null”。因为您的活动不包含 toast_layout,所以它始终为空。
    • 我的自定义 toast 没有显示,因为我使用新的约束布局作为自定义 toast 的根视图。一旦我更改为线性布局,一切都运行良好。所以要注意...
    • 真的有人可以解释 findViewById(R.id.toast_layout_root) 的目的吗?无论如何它都会为null,并且只需传递null就可以很好地工作
    • 我也不知道根视图的用途(null),但在官方文档中也存在,如果有人能解释原因,那就太好了! developer.android.com/guide/topics/ui/notifiers/toasts#java
    • 如果您因 findViewById 为空而崩溃,请使用此选项:View layout = inflater.inflate(R.layout.toast_layout,null);
    【解决方案3】:

    见链接here。你找到你的解决方案。并尝试:

    创建自定义 Toast 视图

    如果简单的短信还不够,您可以为 Toast 通知创建自定义布局。要创建自定义布局,请在 XML 或应用程序代码中定义 View 布局,并将根 View 对象传递给 setView (View) 方法。

    例如,您可以使用以下 XML(保存为 toast_layout.xml)为右侧屏幕截图中可见的 toast 创建布局:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/toast_layout_root"
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:background="#DAAA"
    >
    
        <ImageView android:id="@+id/image"
                   android:layout_width="wrap_content"
                   android:layout_height="fill_parent"
                   android:layout_marginRight="10dp"
        />
    
        <TextView android:id="@+id/text"
                  android:layout_width="wrap_content"
                  android:layout_height="fill_parent"
                  android:textColor="#FFF"
        />
    </LinearLayout>
    

    请注意,LinearLayout 元素的 ID 是“toast_layout”。您必须使用此 ID 从 XML 中扩展布局,如下所示:

     LayoutInflater inflater = getLayoutInflater();
     View layout = inflater.inflate(R.layout.toast_layout,
                                    (ViewGroup) findViewById(R.id.toast_layout_root));
    
     ImageView image = (ImageView) layout.findViewById(R.id.image);
     image.setImageResource(R.drawable.android);
     TextView text = (TextView) layout.findViewById(R.id.text);
     text.setText("Hello! This is a custom toast!");
    
     Toast toast = new Toast(getApplicationContext());
     toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
     toast.setDuration(Toast.LENGTH_LONG);
     toast.setView(layout);
     toast.show();
    

    首先,使用 getLayoutInflater()(或 getSystemService())检索 LayoutInflater,然后使用 inflate(int, ViewGroup) 从 XML 中扩展布局。第一个参数是布局资源 ID,第二个参数是根视图。您可以使用此膨胀布局在布局中查找更多 View 对象,因此现在捕获并定义 ImageView 和 TextView 元素的内容。最后,使用 Toast(Context) 创建一个新的 Toast,并设置 Toast 的一些属性,例如重力和持续时间。然后调用 setView(View) 并将膨胀的布局传递给它。您现在可以通过调用 show() 以自定义布局显示 toast。

    注意:除非您打算使用 setView(View) 定义布局,否则不要对 Toast 使用公共构造函数。如果您没有要使用的自定义布局,则必须使用 makeText(Context, int, int) 来创建 Toast。

    【讨论】:

      【解决方案4】:

      我认为互联网上的大多数 customtoast xml 示例都基于相同的来源。

      Android 文档,在我看来已经过时了。不应再使用 fill_parent。我更喜欢将 wrap_content 与 xml.9.png 结合使用。这样,您可以在提供的源大小中定义 toastbackground 的最小大小。

      如果需要更复杂的 toast,则应使用框架或相对布局而不是 LL。

      toast.xml

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/points_layout"
          android:orientation="horizontal"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:background="@drawable/background"
          android:layout_gravity="center"
          android:gravity="center" >
      
       <TextView
          android:id="@+id/points_text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="center"
          android:gravity="center"
          android:layout_margin="15dp"
          android:text="@+string/points_text"
          android:textColor="@color/Green" />
      
      </LinearLayout>
      

      背景.xml

      <?xml version="1.0" encoding="utf-8"?>
      <nine-patch
         xmlns:android="http://schemas.android.com/apk/res/android"
         android:src="@drawable/background_96"
         android:dither="true"/>
      

      background_96 是 background_96.9.png。

      这没有经过很好的测试,感谢提示:)

      【讨论】:

      • @PeterMortensen LinearLayout
      【解决方案5】:

      toast 用于在短时间内显示消息;因此,根据我的理解,您希望通过向其添加图像并更改消息文本的大小和颜色来对其进行自定义。如果这就是您想要做的全部,则无需制作单独的布局并将其膨胀到 Toast 实例。

      默认 Toast 的视图包含一个 TextView 用于在其上显示消息。因此,如果我们有 TextView 的资源 ID 引用,我们就可以使用它。所以下面是你可以做些什么来实现这一点:

      Toast toast = Toast.makeText(this, "I am custom Toast!", Toast.LENGTH_LONG);
      View toastView = toast.getView(); // This'll return the default View of the Toast.
      
      /* And now you can get the TextView of the default View of the Toast. */
      TextView toastMessage = (TextView) toastView.findViewById(android.R.id.message);
      toastMessage.setTextSize(25);
      toastMessage.setTextColor(Color.RED);
      toastMessage.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_fly, 0, 0, 0);
      toastMessage.setGravity(Gravity.CENTER);
      toastMessage.setCompoundDrawablePadding(16);
      toastView.setBackgroundColor(Color.CYAN);
      toast.show();
      

      在上面的代码中你可以看到,你可以通过setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)将图像添加到TextView,无论你想要相对于TextView的哪个位置。

      更新:

      编写了一个构建器类来简化上述目的;链接在这里: https://gist.github.com/TheLittleNaruto/6fc8f6a2b0d0583a240bd78313ba83bc

      查看以上链接中的HowToUse.kt

      输出:

      【讨论】:

      • 这种情况的可能性很小,但是,我认为应该在那里检查TextView,只是为了安全起见,我的意思是空检查或类型检查.以防万一,谷歌决定更改 id 或视图以在 Toast 类中显示文本。无论如何... +1
      • 真的!但是,如果它会被更改,您将无法访问资源 ID,因为它不存在。但即使为了安全起见,NULL 检查也会让你的生活变得轻松。 @DroidDev 感谢您的建议 :)
      【解决方案6】:

      这是我用的

      AllMethodsInOne.java

      public static Toast displayCustomToast(FragmentActivity mAct, String toastText, String toastLength, String succTypeColor) {
      
          final Toast toast;
      
          if (toastLength.equals("short")) {
              toast = Toast.makeText(mAct, toastText, Toast.LENGTH_SHORT);
          } else {
              toast = Toast.makeText(mAct, toastText, Toast.LENGTH_LONG);
          }
      
          View tView = toast.getView();
          tView.setBackgroundColor(Color.parseColor("#053a4d"));
          TextView mText = (TextView) tView.findViewById(android.R.id.message);
      
          mText.setTypeface(applyFont(mAct));
          mText.setShadowLayer(0, 0, 0, 0);
      
          tView.setOnClickListener(new View.OnClickListener() {
      
              @Override
              public void onClick(View v) {
                  toast.cancel();
              }
          });
          tView.invalidate();
          if (succTypeColor.equals("red")) {
              mText.setTextColor(Color.parseColor("#debe33"));
              tView.setBackground(mAct.getResources().getDrawable(R.drawable.toast_rounded_red));
              // this is to show error message
          }
          if (succTypeColor.equals("green")) {
              mText.setTextColor(Color.parseColor("#053a4d"));
              tView.setBackground(mAct.getResources().getDrawable(R.drawable.toast_rounded_green));
              // this is to show success message
          }
      
      
          return toast;
      }
      

      YourFile.java

      打电话的时候写在下面。

      AllMethodsInOne.displayCustomToast(act, "This is custom toast", "long", "red").show();
      

      【讨论】:

      • toast_rounded_red 这个找不到。我们在哪里创建它?
      • @goops17 :这是具有红色、绿色背景的可绘制文件。相反,您可以提供背景颜色...
      【解决方案7】:

      您可以下载代码here

      第 1 步:

      <?xml version="1.0" encoding="utf-8"?>
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:paddingBottom="@dimen/activity_vertical_margin"
          android:paddingLeft="@dimen/activity_horizontal_margin"
          android:paddingRight="@dimen/activity_horizontal_margin"
          android:paddingTop="@dimen/activity_vertical_margin"
          tools:context=".MainActivity">
      
          <Button
              android:id="@+id/btnCustomToast"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Show Custom Toast" />
        </RelativeLayout>
      

      第 2 步:

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="horizontal"
          android:gravity="center"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">
      
              <ImageView
                  android:id="@+id/custom_toast_image"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:src="@mipmap/ic_launcher"/>
      
              <TextView
                  android:id="@+id/custom_toast_message"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:text="My custom Toast Example Text" />
      
      </LinearLayout>
      

      第 3 步:

      import android.support.v7.app.AppCompatActivity;
      import android.os.Bundle;
      import android.view.Gravity;
      import android.view.LayoutInflater;
      import android.view.View;
      import android.view.ViewGroup;
      import android.widget.Button;
      import android.widget.Toast;
      
      public class MainActivity extends AppCompatActivity {
      
      
          private Button btnCustomToast;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              btnCustomToast= (Button) findViewById(R.id.btnCustomToast);
              btnCustomToast.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
      
                      // Find custom toast example layout file
                      View layoutValue = LayoutInflater.from(MainActivity.this).inflate(R.layout.android_custom_toast_example, null);
                      // Creating the Toast object
                      Toast toast = new Toast(getApplicationContext());
                      toast.setDuration(Toast.LENGTH_SHORT);
      
                      // gravity, xOffset, yOffset
                      toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                      toast.setView(layoutValue);//setting the view of custom toast layout
                      toast.show();
                  }
              });
          }
      }
      

      【讨论】:

        【解决方案8】:

        MainActivity.java 文件的代码。

        package com.android_examples.com.toastbackgroundcolorchange;
        
        import android.app.Activity;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;
        import android.widget.Toast;
        public class MainActivity extends Activity {
        
         Button BT;
         @Override
         protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
        
         BT = (Button)findViewById(R.id.button1);
         BT.setOnClickListener(new View.OnClickListener() {
        
         @Override
         public void onClick(View v) {
        
         Toast ToastMessage = Toast.makeText(getApplicationContext(),"Change Toast Background color",Toast.LENGTH_SHORT);
         View toastView = ToastMessage.getView();
         toastView.setBackgroundResource(R.layout.toast_background_color);
         ToastMessage.show();
        
         }
         });
         }
        }
        

        activity_main.xml 布局文件的代码。

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tools="http://schemas.android.com/tools"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:paddingBottom="@dimen/activity_vertical_margin"
         android:paddingLeft="@dimen/activity_horizontal_margin"
         android:paddingRight="@dimen/activity_horizontal_margin"
         android:paddingTop="@dimen/activity_vertical_margin"
         tools:context="com.android_examples.com.toastbackgroundcolorchange.MainActivity" >
        
         <Button
         android:id="@+id/button1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_centerHorizontal="true"
         android:layout_centerVertical="true"
         android:text="CLICK HERE TO SHOW TOAST MESSAGE WITH DIFFERENT BACKGROUND COLOR INCLUDING BORDER" />
        
        </RelativeLayout>
        

        在 res->layout 文件夹中创建的 toast_background_color.xml 布局文件的代码。

        <?xml version="1.0" encoding="utf-8"?>
        <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        
         <stroke
            android:width="3dp"
            android:color="#ffffff" ></stroke>
        <padding android:left="20dp" android:top="20dp"
            android:right="20dp" android:bottom="20dp" />
        <corners android:radius="10dp" />
        <gradient android:startColor="#ff000f"
            android:endColor="#ff0000"
            android:angle="-90"/>
        
        </shape>
        

        【讨论】:

          【解决方案9】:

          toast 的自定义布局,custom_toast.xml:

          <LinearLayout
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical" android:layout_width="match_parent"
              android:layout_height="match_parent">
              <TextView
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:text="Custom Toast"
                  android:gravity="center"
                  android:id="@+id/custom_toast_text"
                  android:typeface="serif"
                  android:textStyle="bold"
                  />
          </LinearLayout>
          

          还有 Java 方法(只需将 toast 消息传递给此方法):

          public void toast(String message)
          {
              Toast toast = new Toast(context);
              View view = LayoutInflater.from(context).inflate(R.layout.image_custom, null);
              TextView textView = (TextView) view.findViewById(R.id.custom_toast_text);
              textView.setText(message);
              toast.setView(view);
              toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 0);
              toast.setDuration(Toast.LENGTH_LONG);
              toast.show();
          }
          

          【讨论】:

            【解决方案10】:

            //自定义toast类,你可以根据需要显示自定义或默认toast)

            public class ToastMessage {
                private Context context;
                private static ToastMessage instance;
            
                /**
                 * @param context
                 */
                private ToastMessage(Context context) {
                    this.context = context;
                }
            
                /**
                 * @param context
                 * @return
                 */
                public synchronized static ToastMessage getInstance(Context context) {
                    if (instance == null) {
                        instance = new ToastMessage(context);
                    }
                    return instance;
                }
            
                /**
                 * @param message
                 */
                public void showLongMessage(String message) {
                    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
                }
            
                /**
                 * @param message
                 */
                public void showSmallMessage(String message) {
                    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                }
            
                /**
                 * The Toast displayed via this method will display it for short period of time
                 *
                 * @param message
                 */
                public void showLongCustomToast(String message) {
                    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
                    View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
                    TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
                    msgTv.setText(message);
                    Toast toast = new Toast(context);
                    toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
                    toast.setDuration(Toast.LENGTH_LONG);
                    toast.setView(layout);
                    toast.show();
            
            
                }
            
                /**
                 * The toast displayed by this class will display it for long period of time
                 *
                 * @param message
                 */
                public void showSmallCustomToast(String message) {
            
                    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
                    View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
                    TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
                    msgTv.setText(message);
                    Toast toast = new Toast(context);
                    toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
                    toast.setDuration(Toast.LENGTH_SHORT);
                    toast.setView(layout);
                    toast.show();
                }
            
            }
            

            【讨论】:

              【解决方案11】:

              自定义吐司的简单方法,

              private void MsgDisplay(String Msg, int Size, int Grav){
                  Toast toast = Toast.makeText(this, Msg, Toast.LENGTH_LONG);
                  TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
                  v.setTextColor(Color.rgb(241, 196, 15));
                  v.setTextSize(Size);
                  v.setGravity(Gravity.CENTER);
                  v.setShadowLayer(1.5f, -1, 1, Color.BLACK);
                  if(Grav == 1){
                      toast.setGravity(Gravity.BOTTOM, 0, 120);
                  }else{
                      toast.setGravity(Gravity.BOTTOM, 0, 10);
                  }
                  toast.show();
              }
              

              【讨论】:

                【解决方案12】:

                为避免 layout_* 参数未正确使用的问题,您需要确保在扩展自定义布局时指定正确的 ViewGroup 作为父级。

                许多示例在此处传递 null,但您可以将现有的 Toast ViewGroup 作为父级传递。

                val toast = Toast.makeText(this, "", Toast.LENGTH_LONG)
                val layout = LayoutInflater.from(this).inflate(R.layout.view_custom_toast, toast.view.parent as? ViewGroup?)
                toast.view = layout
                toast.show()
                

                在这里,我们将现有的 Toast 视图替换为自定义视图。一旦您参考了您的布局“布局”,您就可以更新它可能包含的任何图像/文本视图。

                此解决方案还可以防止任何“未附加到窗口管理器的视图”崩溃使用 null 作为父级。

                另外,避免使用 ConstraintLayout 作为自定义布局根,这在 Toast 中使用时似乎不起作用。

                【讨论】:

                  【解决方案13】:
                  val inflater = layoutInflater
                  val container: ViewGroup = findViewById(R.id.custom_toast_container)
                  val layout: ViewGroup = inflater.inflate(R.layout.custom_toast, container)
                  val text: TextView = layout.findViewById(R.id.text)
                  text.text = "This is a custom toast"
                  with (Toast(applicationContext)) {
                      setGravity(Gravity.CENTER_VERTICAL, 0, 0)
                      duration = Toast.LENGTH_LONG
                      view = layout
                      show()
                  }
                  
                  <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/droid"
                                 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"
                                />
                  </LinearLayout>
                  

                  参考:https://developer.android.com/guide/topics/ui/notifiers/toasts

                  【讨论】:

                    【解决方案14】:

                    面向所有 Kotlin 用户

                    您可以创建如下扩展:

                    fun FragmentActivity.showCustomToast(message : String,color : Int) {
                     val toastView = findViewById<TextView>(R.id.toast_view)
                     toastView.text = message
                     toastView.visibility = View.VISIBLE
                     toastView.setBackgroundColor(color)
                    
                     // create a daemon thread
                     val timer = Timer("schedule", true)
                    
                     // schedule a single event
                     timer.schedule(2000) {
                        runOnUiThread { toastView.visibility = View.GONE }
                     }
                    }
                    

                    【讨论】:

                      【解决方案15】:

                      创建我们自己的自定义Toast非常简单。

                      只需按照以下步骤操作即可。

                      第一步

                      创建您想要的自定义布局

                      <?xml version="1.0" encoding="utf-8"?>
                      <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
                          xmlns:app="http://schemas.android.com/apk/res-auto"
                          xmlns:tools="http://schemas.android.com/tools"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:backgroundTint="@color/black"
                          android:orientation="vertical"
                          android:padding="@dimen/size_10dp"
                          app:cardCornerRadius="@dimen/size_8dp"
                          app:cardElevation="@dimen/size_8dp">
                      
                          <TextView
                              android:id="@+id/txt_message"
                              android:layout_width="wrap_content"
                              android:layout_height="wrap_content"
                              android:padding="@dimen/size_12dp"
                              android:textAlignment="center"
                              android:textColor="@color/white"
                              android:textSize="@dimen/text_size_16sp"
                              tools:text="Hello Test!!" />
                      
                      </androidx.cardview.widget.CardView>
                      

                      第二步

                      现在创建以Toast 扩展的自定义类。

                      import android.content.Context;
                      import android.view.LayoutInflater;
                      import android.view.View;
                      import android.widget.TextView;
                      import android.widget.Toast;
                      
                      import com.shop.shoppinggare.R;
                      
                      import org.apache.commons.lang3.StringUtils;
                      import org.w3c.dom.Text;
                      
                      public class CustomToast extends Toast {
                          private Context context;
                          private String message;
                      
                          public CustomToast(Context context, String message) {
                              super(context);
                              this.context = context;
                              this.message = message;
                              View view = LayoutInflater.from(context).inflate(R.layout.toast_custom, null);
                              TextView txtMsg = view.findViewById(R.id.txt_message);
                              txtMsg.setText(StringUtils.capitalize(message));
                              setView(view);
                              setDuration(Toast.LENGTH_LONG);
                      
                          }
                      
                      
                      }
                      

                      我们已经创建了自定义 toast。

                      第三步

                      现在,最后,我们该如何使用它。

                      new CustomToast(contex,"message").show();
                      

                      享受!!

                      【讨论】:

                        【解决方案16】:

                        Heads Up, Updates to toasts in Android 11

                        来自后台的自定义 toast 被阻止,Android 11 提供保护 用户通过弃用自定义 toast 视图。出于安全原因和 保持良好的用户体验,系统会阻止包含 如果这些 toasts 是由应用程序从后台发送的,则自定义视图 以 Android 11 为目标。

                        addCallback() 在 Android R 中添加的方法如果您想在 toast(文本或自定义)出现或消失时收到通知。

                        toast API changes 中最重要的文字,对于面向 Android 11 的应用getView() 方法在您访问它时返回 null,因此,请确保保护您的应用免受 FATAL EXCEPTION,您知道的我的意思:)

                        如果适用,请改用小吃店。

                        建议您尽可能使用小吃店。如果 您的应用程序的用例会阻止您使用小吃吧,例如何时 您需要在您的应用程序处于 背景,您仍然可以使用文本敬酒,因为它们不是 受到新行为变化的限制。

                        有关该主题的更多详细信息,请参阅official docs

                        【讨论】:

                          【解决方案17】:

                          使用这个名为 Toasty 的库,我认为您有足够的灵活性通过以下方法制作自定义吐司 -

                          Toasty.custom(yourContext, "I'm a custom Toast", yourIconDrawable, tintColor, duration, withIcon, 
                          shouldTint).show();
                          

                          您也可以将格式化文本传递给Toasty,这里是code snippet

                          【讨论】:

                            【解决方案18】:

                            自定义 Toast 工作代码

                                public class Toaster {
                            
                                private Context context;
                                private Font font;
                            
                                public Toaster(Context context) {
                                    this.context = context;
                            
                                    font = new Font(context);
                                }
                            
                                public void makeToast(String bread) {
                                    Toast.makeText(context, bread, Toast.LENGTH_SHORT).show();
                                }
                            
                                public void makeLongToast(String bread) {
                                    Toast.makeText(context, bread, Toast.LENGTH_LONG).show();
                                }
                            
                                public void makeCustomViewToast(String bread, ToastType toastType) {
                                    View toastView = ((Activity) context).getLayoutInflater().inflate(R.layout.toaster_toast_card_layout, null, false);
                                    CardView toastCardView = toastView.findViewById(R.id.toaster_toast_card_view);
                                    ImageView toastIcon = toastView.findViewById(R.id.toaster_toast_image_view);
                                    TextView toastTextView = toastView.findViewById(R.id.toaster_toast_text_view);
                            
                                    int color = context.getResources().getColor(toastType.getColor());
                                    toastCardView.setCardBackgroundColor(color);
                            
                                    toastTextView.setTypeface(font.saralaBold);
                                    toastTextView.setText(bread);
                            
                                    Drawable icon = context.getResources().getDrawable(toastType.getIcon());
                                    toastIcon.setImageDrawable(icon);
                            
                                    Toast toast = Toast.makeText(context, Text.EMPTY, Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, (int) (InterfaceUtil.getScreenHeight(context) * 0.25f));
                                    toast.setView(toastView);
                                    toast.show();
                                }
                            
                            }
                            

                            【讨论】:

                              最近更新 更多