《Android Dev Guide》系列教程15:用户通知(2)Toast通知的创建
懒骨头(http://blog./iamlazybone)
Toast通知的创建
一个toast通知是从当前窗口弹出的一个信息。它只占能满足文本信息现实的一块区域,并且下面的activity处于可见并且可操作状态。信息会自动的渐隐渐现,不会接受用户的操作。
上图显示了闹铃程序中的一个toast的例子。一旦闹铃程序开启,一个toast就会被显示。
基础知识
首先,通过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();
这个例子详细演示了显示Toast的每个步骤,非常的完整。你也可以使用自己的布局来显示,不仅仅是一个文本,后面的章节会提到。
你也可以这样显示Toast:
- Toast.makeText(context, text, duration).show();
Toast的显示位置
标准的Toast显示在屏幕的正下方,左右居中显示。你也可以用setGravity(int,int,int)方法来自定义位置,例如:
- toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
如果你想让toast往右边偏移一下,增加第二个参数,往下的话增加第二个参数。
创建自定义Toast布局
有时一个简单的文本是不够的,你可以自定义一个布局。创建一个自定义的xml布局文件或者代码,然后把根view传递给setView()方法:
- <LinearLayout xmlns:android="http://schemas./apk/res/android"
- android:id="@+id/toast_layout_root"
- android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="10dp"
- android:background="#DAAA"
- >
- <ImageView android:id="@+id/image"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_marginRight="10dp"
- />
- <TextView android:id="@+id/text"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:textColor="#FFF"
- />
- </LinearLayout>
注意布局的id是toast_layout,你必须使用这个id找到xml,例如:
- LayoutInflater inflater = getLayoutInflater();
- View layout = inflater.inflate(R.layout.toast_layout,
- (ViewGroup) findViewById(R.id.toast_layout_root));
- ImageView image = (ImageView) layout.findViewById(R.id.image);
- image.setImageResource(R.drawable.android);
- TextView text = (TextView) layout.findViewById(R.id.text);
- text.setText("Hello! 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();
首先,使用getLayoutFlater()方法来检索LayoutInflater,然后使用inflate(int,ViewGroup)方法找到xml文件,第一个参数是布局文件的资源id,第二个参数是根View、你可以使用使用inflated布局来找到更多的view和布局对象,现在找到TextView和ImageView这两个元素。最后,使用Toast(Context)方法创建一个新的Toast,并且设置其中的参数。例如位置和时间。然后调用setView(View)并且传递给inflated layout。然后调用show()方法来显示自定义的Toast.
注意:不能使用公共的构造方法除非你调用了setView(View)方法。如果你没有使用自定义的布局,那么只能用makeText(Context,int,int)方法显示。