androidlayoutparamsandroid-toastcustomizing

custom Toast at screen top


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.


Solution

  • I figured this out.

    Starting 4.4+ you have to add the following flag:

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
            mParams.flags = mParams.flags | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
    }
    

    This will allow your toast to be positioned all the way to the top.