请在回答标准例程之前阅读问题以打印Toast 🙂
我想在屏幕的左上角显示自定义Toast.我使用此代码创建Toast:
Toast mFixedToast = new Toast(getApplicationContext());
mFixedToast.setDuration(timeout);
mFixedToast.setView(myInflatedLayout);
mFixedToast.setGravity(Gravity.TOP|Gravity.FILL_HORIZONTAL, 0, 0);
mFixedToast.setMargins(0,0);
然而,在一些设备中,例如三星Galaxy S4,吐司不是位于(0,0),而是具有40-50像素的边缘.许多其他设备按预期工作.
我很肯定WindowManager添加了边距(Toast视图作为TYPE_TOAST类型的视图添加到WindowManager)
这是为什么?可以修改吗?请看下面的代码,我已经将Toast.java克隆到我自己的类中,并隔离了将视图添加到WM的行:
// LayoutParams for the TOAST view ... tried to change params.type but no luck.
final WindowManager.LayoutParams params = mParams;
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.windowAnimations = android.R.style.Animation_Toast;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
mWM = (WindowManager)mView.getContext().getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
mParams.gravity = gravity;
// CHECKED these all are 0 !!!
mParams.x = mX; mParams.y = mY;
mParams.verticalMargin = mVerticalMargin;
mParams.horizontalMargin = mHorizontalMargin;
.
.
if (localLOGV) Log.v(TAG, "ADD! " + mView + " in " + this+" with "+mX+","+mY+","+mVerticalMargin+","+mHorizontalMargin);
mWM.addView(mView, mParams);
所以看起来是WindowManager在这些设备上添加这个边距.看起来像一个安全区域或类似的东西,但我无法找到可以改变的地方(或者是否).
帮助赞赏.