Android Toast详解

一般的Toast我就不说了,我这里主要讲一下,自定义toast包括自定义内容和显示的位置

现在Toast有了新情况,在安卓11,现在大家都用SnackBar

 

 

 效果图

 

Toast代码

private void midToast(String str, int showTime, Context mContext)
    {
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.view_toast_custom, (ViewGroup) findViewById(R.id.viewGroup));
        //ImageView img_logo = (ImageView) view.findViewById(R.id.imageView);
        TextView tv_msg = (TextView) view.findViewById(R.id.textView);
        tv_msg.setText(str);
        Toast toast = new Toast(mContext);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(showTime);
        toast.setView(view);
        toast.show();
    }

bg_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 设置透明背景色 -->
    <solid android:color="@color/cardview_dark_background" />
    <!-- 设置一个黑色边框 -->
    <stroke
        android:width="1px"
        android:color="#FFFFFF" />
    <!-- 设置四个圆角的半径 -->
    <corners
        android:bottomLeftRadius="50px"
        android:bottomRightRadius="50px"
        android:topLeftRadius="50px"
        android:topRightRadius="50px" />
    <!-- 设置一下边距,让空间大一点 -->
    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />
</shape>

view_toast_custom.xml

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

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher_foreground" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:gravity="center"
        android:text="TextView"
        android:textColor="#D8D8D8" />
</LinearLayout>

自定义布局android:src="@drawable/ic_launcher_foreground" />千万记得是默认不是

直接使用

 

midToast("hello",Toast.LENGTH_LONG,this);

 

GitHub地址 下载前给star

 

posted @ 2022-11-01 13:13  Z_Chan  阅读(729)  评论(0编辑  收藏  举报