Toast类实现消息提示框

Toast类实现消息提示框的方式有两种:

  1. 使用静态方法makeText()方法在这里插入图片描述
    以下面那个为例吧,第一个参数是一个上下文对象,第二个参数是要显示的数据,第三个参数是要显示数据的时长。

我们来看看他低层是怎么实现的:

public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
        Toast result = new Toast(context);

        LayoutInflater inflate = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
        TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
        tv.setText(text);
        
        result.mNextView = v;
        result.mDuration = duration;

        return result;
    }

首先是将布局文件实例化成view对象,在来看看这个com.android.internal.R.layout.transient_notification文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="?android:attr/toastFrameBackground">

    <TextView
        android:id="@android:id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
        android:textAppearance="@style/TextAppearance.Toast"
        android:textColor="@color/bright_foreground_dark"
        android:shadowColor="#BB000000"
        android:shadowRadius="2.75"
        />

</LinearLayout>

我的理解就是Toast类就是在低层调用了一个事先写好的只有一个TextView的xml文件。我们只需要在调用makeText时输入相应的数据,就可以直接用了。

  1. 我们在来看第二种方法:直接实例化一个新的Toast对象。
    Toast toast=new Toast(MainActivity.this);
    Toast类的一些主要方法:

setText():显示的内容,支持字符串和字符串资源ID

setGravity():这个是显示的对齐方式,后面两个参数是针对前面对齐方式的x/y偏移量。

setMargin():margin,也就是外边距。比如我们通过Gravity设置显示在左上角,然后设置这两个值为0.5f,则Toast的左上角会现实在屏幕的中央

setView():设置显示内容视图,自定义和他的关系密不可分。

要实现自定的toast很简单,首先先自定义一个xml文件,你想让他显示什么就怎么写。在将这个xml文件用View.inflate方法解析成view类型的,然后直接通过setView()设置就可以了。如:
xml文件:在这里插入图片描述
实现:
在这里插入图片描述
效果:
在这里插入图片描述

发布了18 篇原创文章 · 获赞 8 · 访问量 378

猜你喜欢

转载自blog.csdn.net/qq_34423913/article/details/103681904