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

问题描述 投票:101回答:13

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

android toast
13个回答
178
投票

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


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

}

0
投票

简单的方式来定制吐司,

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

0
投票

为避免layout_ * params未正确使用的问题,您需要确保在自定义布局膨胀时指定正确的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中使用时似乎不起作用。


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


31
投票

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。

输出:


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


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。


1
投票

这是我用的

all method SI none.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;
}

your file.Java

虽然打电话只是写下面。

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

1
投票

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

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>

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。

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


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

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

0
投票

烤面包的自定义布局,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();
}
© www.soinside.com 2019 - 2024. All rights reserved.