Android 上的自定义吐司:一个简单的例子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11288475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:44:49  来源:igfitidea点击:

Custom toast on Android: a simple example

androidtoast

提问by Sandy

I'm new to Android programming. What is a simple example showing a custom toast notification on Android?

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

回答by Dipak Keshariya

Use the below code of a custom Toast. It may help you.

使用以下自定义 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

主活动.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();

And check out the below links also for a custom Toast.

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

Custom Toast with Analog Clock

带模拟时钟的自定义 Toast

YouTube: Creating Custom Toast With Button in Android Studio

YouTube:在 Android Studio 中使用按钮创建自定义 Toast

回答by TheLittleNaruto

A toast is for showing messages for short intervals of time; So, as per my understanding, you would like to customize it with adding an image to it and changing size, color of the message text. If that is all, you want to do, then there is no need to make a separate layout and inflate it to the Toast instance.

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

The default Toast's view contains a TextViewfor showing messages on it. So, if we have the resource id reference of that TextView, we can play with it. So below is what can you do to achieve this:

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

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

In above code you can see, you can add image to TextView via setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)whichever position relative to TextView you want to.

在上面的代码中,您可以看到,您可以通过setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)相对于 TextView 的任何位置将图像添加到 TextView 。

Update:

更新:

Have written a builder class to simplify the above purpose; Here is the link: https://gist.github.com/TheLittleNaruto/6fc8f6a2b0d0583a240bd78313ba83bc

编写了一个builder类来简化上述目的;这是链接:https: //gist.github.com/TheLittleNaruto/6fc8f6a2b0d0583a240bd78313ba83bc

Check the HowToUse.ktin above link.

检查HowToUse.kt上面的链接。

Output:

输出:

Enter image description here

在此处输入图片说明

回答by ρяσ?ρ?я K

STEP 1:

第1步:

First create a layout for a custom toast in res/layout/custom_toast.xml:

首先为自定义 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_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>

STEP 2:In the Activity code, get the above custom view and attach to Toast:

STEP 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();

For more help see how we Create custom Toast in Android:

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

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

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

回答by Deepak Swami

See link here. You find your solution. And try:

请参阅此处的链接。你找到你的解决方案。并尝试:

Creating a Custom Toast View

创建自定义 Toast 视图

If a simple text message isn't enough, you can create a customized layout for your toast notification. To create a custom layout, define a View layout, in XML or in your application code, and pass the root View object to the setView (View) method.

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

For example, you can create the layout for the toast visible in the screenshot to the right with the following XML (saved as toast_layout.xml):

例如,您可以使用以下 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>

Notice that the ID of the LinearLayout element is "toast_layout". You must use this ID to inflate the layout from the XML, as shown here:

请注意,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();

First, retrieve the LayoutInflater with getLayoutInflater() (or getSystemService()), and then inflate the layout from XML using inflate(int, ViewGroup). The first parameter is the layout resource ID and the second is the root View. You can use this inflated layout to find more View objects in the layout, so now capture and define the content for the ImageView and TextView elements. Finally, create a new Toast with Toast(Context) and set some properties of the toast, such as the gravity and duration. Then call setView(View) and pass it the inflated layout. You can now display the toast with your custom layout by calling show().

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

Note: Do not use the public constructor for a Toast unless you are going to define the layout with setView(View). If you do not have a custom layout to use, you must use makeText(Context, int, int) to create the Toast.

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

回答by nirav kalola

You can download code here.

您可以在此处下载代码。

Step 1:

第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>

Step 2:

第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>

Step 3:

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

回答by Sai Gopi N

Custom layout for toast, custom_toast.xml:

吐司的自定义布局,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>

And the Java method (just pass toast message to this method):

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

回答by Andrew Kelly

To avoid problems with layout_* params not being properly used, you need to make sure that when you inflate your custom layout that you specify a correct ViewGroup as a parent.

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

Many examples pass null here, but instead you can pass the existing Toast ViewGroup as your parent.

许多示例在此处传递 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()

Here we replace the existing Toast view with our custom view. Once you have a reference to your layout "layout" you can then update any images/text views that it may contain.

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

This solution also prevents any "View not attached to window manager" crashes from using null as a parent.

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

Also, avoid using ConstraintLayout as your custom layout root, this seems to not work when used inside a Toast.

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

回答by Fahim Parkar

This is what I used

这是我用的

AllMethodsInOne.java

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

你的文件.java

While calling just write below.

打电话时只写在下面。

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

回答by ornay odder

I think most of customtoast xml-examples throughout the Internet are based on the same source.

我认为整个 Internet 上的大多数 customtoast xml-examples 都基于相同的来源。

The Android documentation, which is very outdated in my opinion. fill_parent should not be used any more. I prefer using wrap_content in combination with a xml.9.png. That way you can define the minimum size of toastbackground throughout the size of the provided source.

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

If more complex toasts are required, frame or relative layout should be used instead of LL.

如果需要更复杂的 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>

background.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 is background_96.9.png.

background_96 是 background_96.9.png。

This is not tested very well, and hints are appreciated :)

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

回答by Waruna Manjula

Code for MainActivity.java file.

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

 }
 });
 }
}

Code for activity_main.xml layout file.

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>

Code for toast_background_color.xml layout file created in res->layout folder.

在 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>