android 自定义Toast 显示时长 样式

时间:2025-02-08 15:24:53

吐司(Toast),在Android开发中主要是提示功能,但是有时候系统原生的不能满足我们的需求,只用自定义才能解决,下面是一种自定义的方式


1、首先是布局文件(就是你Toast显示的样式)


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:andro

    android:layout_width="80dp"

    android:layout_height="30dp"

    android:padding="10dp"

    android:gravity="center"

    android:background="@drawable/toaststyle"

    android:orientation="horizontal">


    <ImageView

        android:layout_width="30dp"

        android:layout_height="30dp"

        android:/>


    <TextView

        android:

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_weight="1"

        android:shadowColor="#bbfcd603"

        android:shadowRadius="2.75"

        android:textColor="#ffffff"

        />

</LinearLayout>


2、style样式


<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:andro>

    <solid android:color="#ff0000" />

    <corners android:topLeftRadius="10dp"

        android:topRightRadius="10dp"

        android:bottomRightRadius="10dp"

        android:bottomLeftRadius="10dp"/>

</shape>


3、Toast工具类(这才是核心)

public class ShowToastUtil {


    private static TextView mTextView;

    private static ImageView mImageView;


    public static void showToast(Context context, String message,int cnt) {


        final Timer timer = new Timer();

        //加载Toast布局

        View toastRoot = LayoutInflater.from(context).inflate(.toast, null);

        //初始化布局控件

        mTextView = (TextView) (.message);

        mImageView = (ImageView) (.imageView);

        //为控件设置属性

        mTextView.setText(message);

        mImageView.setImageResource(.ic_launcher);

        //Toast的初始化

        final Toast toastStart = new Toast(context);

        //获取屏幕高度

        WindowManager wm = (WindowManager) (Context.WINDOW_SERVICE);

        int height = ().getHeight();

        //ToastY坐标是屏幕高度的1/3,不会出现不适配的问题

        (Gravity.TOP, 0, height / 3);

        (Toast.LENGTH_LONG);

        (toastRoot);

        (new TimerTask() {

            @Override

            public void run() {

                ();

            }

        }, 0, 3000);  //Toast  long默认显示的是3000毫秒,所以设置成3000

        new Timer().schedule(new TimerTask() {

            @Override

            public void run() {

                ();

                ();

            }

        }, cnt );

    }


4、在调用的的地方设置显示时长


findViewById(.tv).setOnClickListener(new () {

    @Override

    public void onClick(View v) {

        ShowToastUtil.showToast(,"第一个自定义的Toast",30000);

    }

});