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

时间:2012-07-02 06:06:04

标签: android toast

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

17 个答案:

答案 0 :(得分:176)

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

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

答案 1 :(得分:30)

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中。

<强>输出:

Enter image description here

答案 2 :(得分:15)

第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步:在活动代码中,获取上述自定义视图并附加到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

答案 3 :(得分:4)

请参阅链接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 with Toast(Context)并设置toast的一些属性,例如重力和持续时间。然后调用setView(View)并将其传递给膨胀的布局。现在,您可以通过调用show()来显示带有自定义布局的Toast。

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

答案 4 :(得分:2)

Heads Up, Updates to toasts in Android 11

来自后台的自定义吐司被阻止,Android 11保护 用户弃用自定义的Toast视图。出于安全考虑, 保持良好的用户体验,系统会阻止包含以下内容的吐司 自定义视图(如果这些吐司是由应用程序从后台发送的) 以Android 11为目标。

在Android R中添加了

addCallback()方法,如果您想在烤面包(文本或自定义)出现或消失时收到通知。

toast API changes中最重要的文本,对于以Android 11为目标的应用getView()方法在您访问时返回null,因此,请确保保护您的应用不受致命威胁例外,您知道我的意思:)

使用小吃店代替。

建议您尽可能使用小吃店。如果 您应用的用例会阻止您使用小吃店,例如 您需要在应用处于运行状态时向用户发送消息 背景,您仍然可以使用文本吐司,因为它们不是 受新行为更改的限制。

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

答案 5 :(得分:1)

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

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

如果需要更复杂的吐司,则应使用框架或相对布局而不是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是background_96.9.png。

这个测试得不是很好,并且提示值得赞赏:)

答案 6 :(得分:1)

这是我用的

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, tText, Toast.LENGTH_SHORT);
    } else {
        toast = Toast.makeText(mAct, tText, 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();

答案 7 :(得分:1)

您可以下载代码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 :(得分:1)

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

只需执行以下步骤。

第1步

创建所需的自定义布局

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

第2步

现在创建以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);

    }


}

我们创建了自定义吐司。

第3步

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

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

享受!

答案 9 :(得分:0)

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

library(janitor)
library(dplyr)
library(lubridate)
coalesce(excel_numeric_to_date(as.numeric(sheet1$col4)),
         dmy(sheet1$col4))
#[1] "2020-01-01" "2006-06-12" "2007-06-06" "2019-02-02"

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

答案 10 :(得分:0)

对于所有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 }
 }
}

答案 11 :(得分:0)

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

答案 12 :(得分:0)

为避免未正确使用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 :(得分:0)

自定义Toast的简单方法,

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

答案 14 :(得分:0)

//自定义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();
    }

}

答案 15 :(得分:0)

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

答案 16 :(得分:0)

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-&gt;布局文件夹中创建的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>
相关问题