Android消息提示框Toast
Toast是Android中一种简易的消息提示框。和Dialog不一样的是,Toast是没有焦点的,toast提示框不能被用户点击,而且Toast显示的时间有限,toast会根据用户设置的显示时间后自动消失。
创建Toast的方法总共有2种:
1.Toast.makeText(Context context, (CharSequence text)/( int resId), int duration)
参数:context是指上下文对象,通常是当前的Activity,text是指自己写的消息内容,resId指显示内容引用Resource的那条数据,duration指Toast的显示时间,Toast默认有LENGTH_SHORT和LENGTH_LONG两常量,分别表示时间长和短,也可以自定义时间,如:5000表示显示5秒。用此方法获得Toast对象之后调用.show()方法即可显示消息。
2.自定义Toast,通过Toast toast = new Toast(Context context)获得Toast对象,调用.show()方法即可显示消息。
toast.setDuration(duration)设置显示时间,
toast.setGravity(gravity, xOffset, yOffset)设置显示位置,三个参数分别表示(起点位置,水平位移,垂直位移),
toast.setMargin(float horizontalMargin, float verticalMargin)以横向和纵向的百分比设置显示位置,参数均为float类型(水平位移正右负左,竖直位移正上负下),
toast.setText(text)设置消息内容,
toast.setView(view)设置Toast显示的视图组件。
实例:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp" >
<Button
android:id="@+id/simpleToast"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="默认" >
</Button>
<Button
android:id="@+id/simpleToastWithCustomPosition"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="自定义显示位置" >
</Button>
<Button
android:id="@+id/imageToast"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="带图片" >
</Button>
<Button
android:id="@+id/customToast"
android:layout_width="fill_parent"
android:layout_height="wrap_content"</