前言:关于android Toast你了解多少?Toast的实现原理是什么?如何实现自己的Toast?现在我就带你实现自己的Toast!我们可以实现以下功能:
1.自定义Toast的样式,可以增加button,checkbox等等
2.可以完成控制Toast的显示时间已经显示位置,并且可以动态的改变Toast的位置
3.可以完成控制Toast的显示动画和消失动画,可能还有意向不到的收获,实现一些复杂动画
1.Toast 原理
看android源码我们可以知道,Toast的底层实现是通过WindowManager实现的我相信大家都对WindowManager有了一定的了解,如果不了解自行了解。查找源码Toast可以看到有一个叫做mTN的成员变量,这个变量至关重要Toast的显示和隐藏都是通过这个变量处理的,下面贴出TN的源码就可以发现Toast的真相;
private static class TN extends ITransientNotification.Stub {
final Runnable mShow = new Runnable() {
@Override
public void run() {
handleShow();
}
};
final Runnable mHide = new Runnable() {
@Override
public void run() {
handleHide();
// Don't do this in handleHide() because it is also invoked by handleShow()
mNextView = null;
}
};
private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();
final Handler mHandler = new Handler();
int mGravity;
int mX, mY;
float mHorizontalMargin;
float mVerticalMargin;
View mView;
View mNextView;
WindowManager mWM;
TN() {
// XXX This should be changed to use a Dialog, with a Theme.Toast
// defined that sets up the layout params appropriately.
final WindowManager.LayoutParams params = mParams;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.format = PixelFormat.TRANSLUCENT;
params.windowAnimations = com.android.internal.R.style.Animation_Toast;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.setTitle("Toast");
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
/// M: [ALPS00517576] Support multi-user
params.privateFlags = WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
}
/**
* schedule handleShow into the right thread
*/