温故知新-Toast学习笔记

来源:互联网 发布:java icon标签 编辑:程序博客网 时间:2024/04/28 15:02

1.Toast

Toast为应用操作提供了一种简单的反馈机制,它是一个小型的弹出窗口,只占用足够其显示消息内容的空间,而不影响当前activity的可见与交互。例如,它会在你退出未发送的邮件时,触发一条内容为”draft saved”的toast提示你能稍后继续编辑这条邮件。toast会自动在超时后消失。

如果需要用户回馈一个状态消息,可以考虑使用notification。

2.基本用法

首先,你需要用maketext()方法来实例化一个toast对象,这个方法有三个参数:应用的context,需要显示的文本消息,和需要显示的时间。它的返回值是一个实例化的toast对象。用show()方法来显示。如下所示:

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

3.指定toast的位置

一个标准的toast出现在靠近屏幕下方垂直居中的位置。你可以使用setGravity(int, int, int)方法改变他的位置,这个方法有3个参数。一个gravity常量,一个x轴偏移量,和一个y轴偏移量。

例如,如果你想让一个toast出现在屏幕的右上角。你可以这么设置参数:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

如果你想向右移动位置,增加第二个参数的值;向下移动位置,增加第三个参数的值。

4.创建一个自定义的Toast视图

如果一个简单的文本消息无法满足需求。你可以为你的toast指定一个布局。创建一个自定义布局,你需要定义一个xml布局文件。并且调用setView(View)方法。将根节点view当做参数传递给它。

例如,你可以用下面的代码为toast创建一个布局文件(保存为toast_layout.xml):

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

注意这个LinearLayout元素的ID是“toast_layout_root”.你需要使用这个ID去inflate这个布局,如下所示:

LayoutInflater inflater = getLayoutInflater();View layout = inflater.inflate(R.layout.custom_toast,                (ViewGroup) findViewById(R.id.custom_toast_container));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();

首先,调用getLayoutInflater()或者getSystemService()方法获得LayoutInflater对象,然后用inflate(int, ViewGroup)方法inflate这个布局,第一个参数是需要inflate的的XML布局ID,第二个参数是父视图。你可以得到这个inflate过的layout里的其他视图对象。现在,得到并设置ImageView和TextView的内容。最后,用构造方法Toast(Context)创建一个toast对象,并且设置一些所需的属性例如位置,时长,然后调用setView(View)方法并将inflate后的layout当做参数传递给它。现在你可以调用show()方法来显示你自定义的toast了。

意:除非你打算用setView(View)方法来来定义Toast的布局,否则请勿使用toast的公共构造方法创建一个Toast。如果你没有自定义Toast的布局,请务必使用makeText(Context, int, int)方法来创建一个Toast。

0 0
原创粉丝点击