Please read the question before answering with your standard routine to print a Toast :)
I'd like to display a Custom Toast at the top left corner of the screen. I use this code to create the 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);
However, in some devices, for example Samsung Galaxy S4, the toast is not positioned at (0,0), but with a margin like 40-50 pixels. Many other devices work as expected.
I am positive the margin is added by the WindowManager (The toast view is added as a View of type TYPE_TOAST to the WindowManager)
Why is that? Can it be modified? Please see the code below, I've cloned Toast.java into my own class and isolated the lines where the View is added to the 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);
So it looks like it's the WindowManager who is adding this margin on those devices. Looks like a safe area or something like that, but I cant find where (or if) this can be changed.
Help appreciated.
Please try the following :
Also check the inflated layout, that might be causing the issue. You might be using the MatchParent for that view and gravity center.
You can try this method to display toast in center of screen. If you want to display toast on top.you can change the
msg.getYOffset()
. Here is code. Try thisI hope this will help you. Happy Coding :)
I figured this out.
Starting 4.4+ you have to add the following flag:
This will allow your toast to be positioned all the way to the top.