如何正确使用Toast进行用户提醒

来源:互联网 发布:安装监控需要网络吗 编辑:程序博客网 时间:2024/06/13 12:21

本篇博客主要介绍如何使用Toast,Toast是Android提供的一个轻量级的用户提醒控件,使用也很简单,就相当一个极简的dialog!!!下面将向您介绍一些Toast的详细用法:

1、普遍使用的方法:

    Context context = getApplicationContext();    CharSequence text = "Hello toast!";    int duration = Toast.LENGTH_SHORT;    Toast toast = Toast.makeText(context, text, duration);    toast.show();

一般情况下,我们都是这样使用Toast的,就跟其他的UI一样,初始化一个UI需要传入一个Context,这里是通过getApplicationContext获取应用程序的上下文!!!

2、设置Toast显示的位置:
一般情况下,Toast显示在屏幕的下半屏幕中,就像下图所示的那样:
这里写图片描述
我们可以通过代码更新Toast显示的位置:

    Context context = getApplicationContext();    CharSequence text = "Hello toast!";    int duration = Toast.LENGTH_SHORT;    Toast toast = Toast.makeText(context, text, duration);    toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);    toast.show();

方法原型:

public void setGravity(int gravity, int xOffset, int yOffset)

这里的参数意义就不介绍,相信您根据名字就可以猜出来!!!

改变位置后的Toast:
这里写图片描述

3、自定义Toast的Layout:
Toast的布局如下所示:

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

在代码中解析layout,并将解析的布局添加至Toast中,具体代码如下所示:

    public void onShowCustomToast(View view) {        LayoutInflater inflater = getLayoutInflater();        View layout = inflater.inflate(R.layout.toast_layout,                null);        TextView text = (TextView) layout.findViewById(R.id.text);        text.setText("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到这里差不多就结束了,有兴趣的朋友可以更加深入的研究学习,在这里就不赘述了!!!

这是我的微信公众号,如果可以的话,希望您可以帮忙关注一下,这将是对我最大的鼓励了,谢谢!!

这里写图片描述

代码稍后会上传至GitHub中:
代码地址:https://github.com/zhuyuqiang2017/Other

0 0
原创粉丝点击