如何自定义一个toast,
1.首先要有一个布局文件,在layout中创建布局文件设置自定义toast控件的显示样式。即toast的布局。
2.创建一个方法,显示我们自定义的toast控件,使用了窗口管理者,将我们的控件转成一个view对象,
添加到窗口管理者中,此外还可以根据Gravity来设置toast的位置,如果不设置toast的位置,后果不堪设想哦!!!
3.将view对象添加到windowManager中
3.将view对象添加到windowManager中
//在窗口中显示toast控件
windowManager.addView(view, params);
4.此外隐藏自定义的toast方法代码如下:
1.首先要有一个布局文件,在layout中创建布局文件设置自定义toast控件的显示样式。即toast的布局。
2.创建一个方法,显示我们自定义的toast控件,使用了窗口管理者,将我们的控件转成一个view对象,
添加到窗口管理者中,此外还可以根据Gravity来设置toast的位置,如果不设置toast的位置,后果不堪设想哦!!!
3.将view对象添加到windowManager中
如果需要,还应该设置toast控件的隐藏方法,即不需要的时候就让toast消失。具体代码如下。
1.布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:id="@+id/ll_toast_address_show"
android:background="@drawable/btn_green_normal"
android:padding="6sp"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
/>
<TextView
android:id="@+id/tv_toast_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="#000000"
android:text="北京移动"
/>
</LinearLayout>
布局文件的样式,
2.定义自定义控件的显示方法
//显示自定义toast
public void showToast(String queryAddress){
//创建一个窗口管理者
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
//把自定义toast布局文件转成view对象
view = View.inflate(getApplicationContext(), R.layout.toast_layout, null);
//获取自定义toast控件中的文本显示控件
TextView tv_toast_address = (TextView) view.findViewById(R.id.tv_toast_address);
//设置toast地址 把传递进来的地址显示在自定义控件的文件显示控件中。
tv_toast_address.setText(queryAddress);
//设置参数。
params = new WindowManager.LayoutParams();
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.flags =
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE//自定义的需要点击
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
params.format = PixelFormat.TRANSLUCENT;
//params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.type = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;//设置为高优先级的类型
//设置吐司位置 左右 效果冲突 以默认效果为主。
params.gravity=Gravity.LEFT | Gravity.TOP;
//设置自定义位置。
params.x = sp.getInt("x", 100);//根据gravity属性来设置距离边框的位置
params.y = sp.getInt("y", 100);
//在窗口中显示toast控件
windowManager.addView(view, params);
}
3.将view对象添加到windowManager中
//在窗口中显示toast控件
windowManager.addView(view, params);
4.此外隐藏自定义的toast方法代码如下:
/**
* 隐藏吐司的操作
*/
public void handleHide() {
// note: checking parent() just to make sure the view has
// been added... i have seen cases where we get here when
// the view isn't yet added, so let's try not to crash.
if (windowManager != null && view!= null) {
windowManager.removeView(view);//移出控件
windowManager= null;
view=null;
}
}