跳转至

Android 自定义Toast

更新日期 2022-9-5
  • 2022-9-5 创建文档

系统自带的Toast一般是灰色背景,黑色文字。有时候我们需要做一些自定义的背景和颜色的Toast

可以依旧使用Toast类和它的机制,但把我们自己的ui替换进去。

自定义背景和文字颜色大小的Toast

这里给一个自定义背景和文字颜色大小的例子。

背景

先在drawable里弄一个背景bg_my_toast.xml

1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="25dp" />
    <solid android:color="#A9EAEAEA" />
</shape>

layout

自定义一个layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_my_toast"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="12dp"
        android:gravity="center"
        android:minWidth="120dp"
        android:text="Warning"
        android:textColor="#C2185B"
        android:textSize="18sp" />
</LinearLayout>

从这里我们也可以看出,除了TextView,我们还可以多放点东西进去。

调用方式

首先根据layout加载view,然后把view交给toast。

这里的Context我们传入Activity

public static void myToast(Context context, String msg) {
    View view = LayoutInflater.from(context).inflate(R.layout.toast_layout, null);
    TextView tv1 = view.findViewById(R.id.tv1);
    tv1.setText(msg);
    Toast toast = new Toast(context);
    toast.setGravity(Gravity.BOTTOM | Gravity.CENTER, 0, 440);
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.setView(view);
    toast.show();
}

本站说明

一起在知识的海洋里呛水吧。广告内容与本站无关。如果喜欢本站内容,欢迎投喂作者,谢谢支持服务器。如有疑问和建议,欢迎在下方评论~

📖AndroidTutorial 📚AndroidTutorial 🙋反馈问题 🔥最近更新 🍪投喂作者

Ads