Android fit system windows

Любая активность размещается в специальном контейнере и пользователь видит её вместе с системными элементами — строкой состояния, панелью навигации. Всё вместе это контролируется классом Window. Но иногда требуется изменить стандартное поведение. Самый простой пример — игры в полноэкранном режиме, когда мы хотим скрыть все лишние элементы с экрана. Другой вариант — полноэкранный режим, но системные элементы накладываются поверх игры. Ещё один вариант — динамическое изменение, когда пользователь начинает прокручивать список вверх, то системная строка состояния исчезает, а при прокрутке вниз снова появляется.

Любая активность может получить доступ к окну Window через метод Activity#getWindow().


Window window = this.getWindow();
System.out.println(window.getClass().getSimpleName()); // PhoneWindow

Аналогично класс Dialog имеет своё окно Dialog#getWindow().

В свою очередь окно содержит всю необходимую информацию о размерах системных элементов и подстраивает все дочерние элементы (вашу активность), чтобы не было нигде зазоров или наложений друг на друга. Реализуется взаимное расположение при помощи специальных отступов Inset.

Поведение Window в разных версиях Android менялась. До KitKat была упрощённая версия не учитывала системные элементы управления. Доступ к ним осуществлялся через метод setSystemUiVisibility(). Также было множество флагов настроек: SYSTEM_UI_FLAG_VISIBLE, SYSTEM_UI_FLAG_FULLSCREEN и другие.

Начиная с KitKat, Android стала поддерживать полупрозрачные системные панели. Появились атрибуты androd:windowTranslucentStatus, android:windowsTranslucentNavigation.

В Lollipop происходит дальнейшая интеграция, системные элементы входят в состав Window и появилась возможность управлять фоном через android:windowDrawsSystemBarBackgrounds.

Мы можем узнать цвета системных элементов.


ImageView image = findViewById(R.id.imageView);

Window window = this.getWindow();
int navigationColor = window.getNavigationBarColor();
int statusBarColor = window.getStatusBarColor();
image.setBackgroundColor(statusBarColor);

android:fitsSystemWindows=»true»

Данный флаг использовался для этой же цели. Сейчас в документации указано, что флаг считается устаревшим с версии API 20.

Данный флаг не будет иметь значения для многих видов макетов типа LinearLayout, FrameLayout. Но есть несколько видов макетов, к которым флаг применить можно. К таким макетам относятся DrawerLayout, CoordinatorLayout, AppBarLayout, CollapsingToolbarLayout, NavigationView.

Лучше вызывать метод onApplyWindowInsets().

Что делать не надо — вручную прописывать размеры строки состояния в ресурсах. Каждое устройство и каждая версия могут иметь свои размеры системных компонентов и ваша попытка видоизменить размеры приведёт к некрасивым последствиям в виде наслоений разных частей компонентов.

Для решения проблемы используйте методы getSystemWindowInsetLeft(), getSystemWindowInsetTop(), getSystemWindowInsetRight(), getSystemWindowInsetBottom() класса WindowInsets/WindowInsetsCompat.

При разработке собственного компонента можете использовать код:


// Kotlin
myView.setOnApplyWindowInsetListener{view, insets ->
    // Ваш код для обработки отступов
	...
	val statusBarSize = insets.systemWindowInsetTop
	
	return insets.consumeSystemWindowInsets()
}

Как уже упоминалось выше, отступы не работают с некоторыми видами макетов. Вы можете переопределить поведение макета, наследуясь от основного макета и переопределяя метод.


// Kotlin
class CustomLayout : LinearLayout {
	override fun onApplyWindowInsets(
	    insets: WindowInsets): WindowInsets {
			// Ваш код для обработки отступов
	        ...
			
	 	    return insets.consumeSystemWindowInsets()
		}
}

BottomNavigationView

Как работать с нижней частью экрана рассказано в статье WindowInsets — Listeners to layouts (12 Apr 2019).

Дополнительное чтение

droidcon NYC 2017 — Becoming a master window fitter🔧 — YouTube

Реклама

Summary of usage of fitsSystemWindows attribute in Android

The fitsSystemWindows attribute is a knowledge point that I involved in learning immersive mode, because it involves the difference between different versions of Android, so it was also in the cloud at the time, so I deliberately organized this attribute today.

Property description

The fitsSystemWindows attribute allows the view to adjust its layout according to the system window; in simple words, whether we consider the system window layout when setting the application layout, here the system window includes the system status bar, navigation bar, input method, etc., including some mobile phone system bands There are virtual buttons at the bottom.

android:fitsSystemWindows=”true” (trigger the padding attribute of View to make room for the system window)
This property can be set for any view, as long as this property is set, all other padding properties of this view are invalid, and the effective condition of this property is only when the transparent status bar (StatusBar) or This property will only take effect in the NavigationBar.

Note: fitsSystemWindows only works on Android 4.4 and above systems, because the StatusBar below 4.4 system has no transparent status.

Application scenario

Under different Android versions, the adaptation of the App status bar and the status bar of the system itself in different versions;
Compatible with mobile phone systems with virtual buttons at the bottom.

1. The default effect

First post a picture of the test layout when the system status bar and navigation bar are not transparently set:

2. The effect after the system window is transparent

When the transparent status bar (StatusBar) and transparent navigation bar (NavigationBar) are set, the effect picture:

Transparent status bar code settings:

//Layout settings
<item name="android:windowTranslucentStatus">true</item>
 //Or code settings
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}

Code setting of transparent navigation bar:

//Layout settings
<item name="android:windowTranslucentNavigation">true</item>
 //Or code settings
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}

If there is one of the above two situations, our status bar (StatusBar) or navigation bar (NavigationBar) will become transparent, and the layout will expand to the position of StatusBar or NavigationBar.

Note: There is a question about the transparent style of the status bar and navigation bar. This is determined by the Android version. There is no transparency effect below 4.4, 4.4~5.0 is fully transparent, and 5.0 is translucent. I used a simulator of version 5.0 or higher for testing, so it is translucent.

3. After setting the properties of fitsSystemWindows

Now it’s time for our key fitsSystemWindows attribute to appear. Just add android:fitsSystemWindows=»true» to the root layout as shown below:

After setting the android:fitsSystemWindows=”true” attribute, a transparent pad with a value equal to the height of the status bar will be automatically added to the transparent status bar; a transparent pad will be added with a paddingBottom equal to the height of the navigation bar

Paste the layout code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:fitsSystemWindows="true"
              android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:background="#66FF4081"
        android:gravity="center"
                 android:text="App title bar"
        android:textSize="30sp"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#0CE3EE"
        android:gravity="center"
                 android:text="App content section"
        android:textSize="30sp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:background="#4188F8"
        android:gravity="center"
                 android:text="App navigation bar"
        android:textSize="30sp"/>
</LinearLayout>

Follow up

Attach a java code to get the status bar StatusBar and a get the height of the navigation bar NavigationBar:

//The return value is the height of the status bar, and the resulting value unit is px
public float getStatusBarHeight() {
    float result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimension(resourceId);
    }
    return result;
}   
  //The return value is the height of the navigation bar, and the resulting value unit is px
public float getNavigationBarHeight() {
    float result = 0;
    int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimension(resourceId);
    }
    return result;
}  



public
static

class
WindowManager.LayoutParams

extends ViewGroup.LayoutParams

implements

Parcelable


Summary

XML attributes

android:windowNoMoveAnimation Flag indicating whether this window should skip movement animations. 

Inherited XML attributes

From class
android.view.ViewGroup.LayoutParams

android:layout_height Specifies the basic height of the view. 

android:layout_width Specifies the basic width of the view. 

Constants

int ALPHA_CHANGED

int ANIMATION_CHANGED

float BRIGHTNESS_OVERRIDE_FULL

Value for screenBrightness and buttonBrightness
indicating that the screen or button backlight brightness should be set
to the hightest value when this window is in front.

float BRIGHTNESS_OVERRIDE_NONE

Default value for screenBrightness and buttonBrightness
indicating that the brightness value is not overridden for this window
and normal brightness policy should be used.

float BRIGHTNESS_OVERRIDE_OFF

Value for screenBrightness and buttonBrightness
indicating that the screen or button backlight brightness should be set
to the lowest value when this window is in front.

int DIM_AMOUNT_CHANGED

int DISPLAY_FLAG_DISABLE_HDR_CONVERSION

Indicates whether this window wants the HDR conversion is disabled.

int FIRST_APPLICATION_WINDOW

Start of window types that represent normal application windows.

int FIRST_SUB_WINDOW

Start of types of sub-windows.

int FIRST_SYSTEM_WINDOW

Start of system-specific window types.

int FLAGS_CHANGED

int FLAG_ALLOW_LOCK_WHILE_SCREEN_ON

Window flag: as long as this window is visible to the user, allow
the lock screen to activate while the screen is on.

int FLAG_ALT_FOCUSABLE_IM

Window flag: when set, inverts the input method focusability of the window.

int FLAG_BLUR_BEHIND

Window flag: enable blur behind for this window.

int FLAG_DIM_BEHIND

Window flag: everything behind this window will be dimmed.

int FLAG_DISMISS_KEYGUARD


This constant was deprecated
in API level 26.
Use FLAG_SHOW_WHEN_LOCKED or
KeyguardManager.requestDismissKeyguard instead.
Since keyguard was dismissed all the time as long as an
activity with this flag on its window was focused,
keyguard couldn’t guard against unintentional touches on
the screen, which isn’t desired.

int FLAG_DITHER


This constant was deprecated
in API level 17.
This flag is no longer used.

int FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS

Flag indicating that this Window is responsible for drawing the background for the
system bars.

int FLAG_FORCE_NOT_FULLSCREEN


This constant was deprecated
in API level 30.
This value became API «by accident», and shouldn’t be used by 3rd party
applications.

int FLAG_FULLSCREEN


This constant was deprecated
in API level 30.
Use WindowInsetsController.hide(int) with Type.statusBars()
instead.

int FLAG_HARDWARE_ACCELERATED

Indicates whether this window should be hardware accelerated.

int FLAG_IGNORE_CHEEK_PRESSES

Window flag: intended for windows that will often be used when the user is
holding the screen against their face, it will aggressively filter the event
stream to prevent unintended presses in this situation that may not be
desired for a particular window, when such an event stream is detected, the
application will receive a CANCEL motion event to indicate this so applications
can handle this accordingly by taking no action on the event
until the finger is released.

int FLAG_KEEP_SCREEN_ON

Window flag: as long as this window is visible to the user, keep
the device’s screen turned on and bright.

int FLAG_LAYOUT_ATTACHED_IN_DECOR


This constant was deprecated
in API level 30.
Use setFitInsetsTypes(int) to determine whether the attached
window will overlap with system bars.

int FLAG_LAYOUT_INSET_DECOR


This constant was deprecated
in API level 30.
Insets will always be delivered to your application.

int FLAG_LAYOUT_IN_OVERSCAN


This constant was deprecated
in API level 30.
Overscan areas aren’t set by any Android product anymore as of Android 11.

int FLAG_LAYOUT_IN_SCREEN

Window flag for attached windows: Place the window within the entire screen, ignoring
any constraints from the parent window.

int FLAG_LAYOUT_NO_LIMITS

Window flag: allow window to extend outside of the screen.

int FLAG_LOCAL_FOCUS_MODE

Flag for a window in local focus mode.

int FLAG_NOT_FOCUSABLE

Window flag: this window won’t ever get key input focus, so the
user can not send key or other button events to it.

int FLAG_NOT_TOUCHABLE

Window flag: this window can never receive touch events.

int FLAG_NOT_TOUCH_MODAL

Window flag: even when this window is focusable (its
FLAG_NOT_FOCUSABLE is not set), allow any pointer events
outside of the window to be sent to the windows behind it.

int FLAG_SCALED

Window flag: a special mode where the layout parameters are used
to perform scaling of the surface when it is composited to the
screen.

int FLAG_SECURE

Window flag: treat the content of the window as secure, preventing
it from appearing in screenshots or from being viewed on non-secure
displays.

int FLAG_SHOW_WALLPAPER

Window flag: ask that the system wallpaper be shown behind
your window.

int FLAG_SHOW_WHEN_LOCKED


This constant was deprecated
in API level 27.
Use R.attr.showWhenLocked or
Activity.setShowWhenLocked(boolean) instead to prevent an
unintentional double life-cycle event.

int FLAG_SPLIT_TOUCH

Window flag: when set the window will accept for touch events
outside of its bounds to be sent to other windows that also
support split touch.

int FLAG_TOUCHABLE_WHEN_WAKING


This constant was deprecated
in API level 20.
This flag has no effect.

int FLAG_TRANSLUCENT_NAVIGATION


This constant was deprecated
in API level 30.
Use Window.setNavigationBarColor(int) with a half-translucent color
instead.

int FLAG_TRANSLUCENT_STATUS


This constant was deprecated
in API level 30.
Use Window.setStatusBarColor(int) with a half-translucent color
instead.

int FLAG_TURN_SCREEN_ON


This constant was deprecated
in API level 27.
Use R.attr.turnScreenOn or
Activity.setTurnScreenOn(boolean) instead to prevent an
unintentional double life-cycle event.

int FLAG_WATCH_OUTSIDE_TOUCH

Window flag: if you have set FLAG_NOT_TOUCH_MODAL, you
can set this flag to receive a single special MotionEvent with
the action
MotionEvent.ACTION_OUTSIDE for
touches that occur outside of your window.

int FORMAT_CHANGED

int LAST_APPLICATION_WINDOW

End of types of application windows.

int LAST_SUB_WINDOW

End of types of sub-windows.

int LAST_SYSTEM_WINDOW

End of types of system windows.

int LAYOUT_CHANGED

int LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS

The window is always allowed to extend into the DisplayCutout areas on the all
edges of the screen.

int LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT

The window is allowed to extend into the DisplayCutout area, only if the
DisplayCutout is fully contained within a system bar or the DisplayCutout
is not deeper than 16 dp, but this depends on the OEM choice.

int LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER

The window is never allowed to overlap with the DisplayCutout area.

int LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES

The window is always allowed to extend into the DisplayCutout areas on the short
edges of the screen.

int MEMORY_TYPE_CHANGED

int MEMORY_TYPE_GPU


This constant was deprecated
in API level 15.
this is ignored, this value is set automatically when needed.

int MEMORY_TYPE_HARDWARE


This constant was deprecated
in API level 15.
this is ignored, this value is set automatically when needed.

int MEMORY_TYPE_NORMAL


This constant was deprecated
in API level 15.
this is ignored, this value is set automatically when needed.

int MEMORY_TYPE_PUSH_BUFFERS


This constant was deprecated
in API level 15.
this is ignored, this value is set automatically when needed.

int ROTATION_ANIMATION_CHANGED

int ROTATION_ANIMATION_CROSSFADE

Value for rotationAnimation which specifies that this
window will fade in or out following a rotation.

int ROTATION_ANIMATION_JUMPCUT

Value for rotationAnimation which specifies that this window
will immediately disappear or appear following a rotation.

int ROTATION_ANIMATION_ROTATE

Value for rotationAnimation which specifies that this
window will visually rotate in or out following a rotation.

int ROTATION_ANIMATION_SEAMLESS

Value for rotationAnimation to specify seamless rotation mode.

int SCREEN_BRIGHTNESS_CHANGED

int SCREEN_ORIENTATION_CHANGED

int SOFT_INPUT_ADJUST_NOTHING

Adjustment option for softInputMode: set to have a window
not adjust for a shown input method.

int SOFT_INPUT_ADJUST_PAN

Adjustment option for softInputMode: set to have a window
pan when an input method is
shown, so it doesn’t need to deal with resizing but just panned
by the framework to ensure the current input focus is visible.

int SOFT_INPUT_ADJUST_RESIZE


This constant was deprecated
in API level 30.
Call Window.setDecorFitsSystemWindows(boolean) with false and
install an OnApplyWindowInsetsListener on your root content view that fits insets
of type Type.ime().

int SOFT_INPUT_ADJUST_UNSPECIFIED

Adjustment option for softInputMode: nothing specified.

int SOFT_INPUT_IS_FORWARD_NAVIGATION

Bit for softInputMode: set when the user has navigated
forward to the window.

int SOFT_INPUT_MASK_ADJUST

Mask for softInputMode of the bits that determine the
way that the window should be adjusted to accommodate the soft
input window.

int SOFT_INPUT_MASK_STATE

Mask for softInputMode of the bits that determine the
desired visibility state of the soft input area for this window.

int SOFT_INPUT_MODE_CHANGED

int SOFT_INPUT_STATE_ALWAYS_HIDDEN

Visibility state for softInputMode: please always hide any
soft input area when this window receives focus.

int SOFT_INPUT_STATE_ALWAYS_VISIBLE

Visibility state for softInputMode: please always make the
soft input area visible when this window receives input focus.

int SOFT_INPUT_STATE_HIDDEN

Visibility state for softInputMode: please hide any soft input
area when normally appropriate (when the user is navigating
forward to your window).

int SOFT_INPUT_STATE_UNCHANGED

Visibility state for softInputMode: please don’t change the state of
the soft input area.

int SOFT_INPUT_STATE_UNSPECIFIED

Visibility state for softInputMode: no state has been specified.

int SOFT_INPUT_STATE_VISIBLE

Visibility state for softInputMode: please show the soft
input area when normally appropriate (when the user is navigating
forward to your window).

int TITLE_CHANGED

int TYPE_ACCESSIBILITY_OVERLAY

Window type: Windows that are overlaid only by a connected AccessibilityService for interception of
user interactions without changing the windows an accessibility service
can introspect.

int TYPE_APPLICATION

Window type: a normal application window.

int TYPE_APPLICATION_ATTACHED_DIALOG

Window type: like TYPE_APPLICATION_PANEL, but layout
of the window happens as that of a top-level window, not
as a child of its container.

int TYPE_APPLICATION_MEDIA

Window type: window for showing media (such as video).

int TYPE_APPLICATION_OVERLAY

Window type: Application overlay windows are displayed above all activity windows
(types between FIRST_APPLICATION_WINDOW and LAST_APPLICATION_WINDOW)
but below critical system windows like the status bar or IME.

int TYPE_APPLICATION_PANEL

Window type: a panel on top of an application window.

int TYPE_APPLICATION_STARTING

Window type: special application window that is displayed while the
application is starting.

int TYPE_APPLICATION_SUB_PANEL

Window type: a sub-panel on top of an application window.

int TYPE_BASE_APPLICATION

Window type: an application window that serves as the «base» window
of the overall application; all other application windows will
appear on top of it.

int TYPE_CHANGED

int TYPE_DRAWN_APPLICATION

Window type: a variation on TYPE_APPLICATION that ensures the window
manager will wait for this window to be drawn before the app is shown.

int TYPE_INPUT_METHOD

Window type: internal input methods windows, which appear above
the normal UI.

int TYPE_INPUT_METHOD_DIALOG

Window type: internal input methods dialog windows, which appear above
the current input method window.

int TYPE_KEYGUARD_DIALOG

Window type: dialogs that the keyguard shows
In multiuser systems shows on all users’ windows.

int TYPE_PHONE


This constant was deprecated
in API level 26.
for non-system apps. Use TYPE_APPLICATION_OVERLAY instead.

int TYPE_PRIORITY_PHONE


This constant was deprecated
in API level 26.
for non-system apps. Use TYPE_APPLICATION_OVERLAY instead.

int TYPE_PRIVATE_PRESENTATION

Window type: Window for Presentation on top of private
virtual display.

int TYPE_SEARCH_BAR

Window type: the search bar.

int TYPE_STATUS_BAR

Window type: the status bar.

int TYPE_SYSTEM_ALERT


This constant was deprecated
in API level 26.
for non-system apps. Use TYPE_APPLICATION_OVERLAY instead.

int TYPE_SYSTEM_DIALOG

Window type: panel that slides out from the status bar
In multiuser systems shows on all users’ windows.

int TYPE_SYSTEM_ERROR


This constant was deprecated
in API level 26.
for non-system apps. Use TYPE_APPLICATION_OVERLAY instead.

int TYPE_SYSTEM_OVERLAY


This constant was deprecated
in API level 26.
for non-system apps. Use TYPE_APPLICATION_OVERLAY instead.

int TYPE_TOAST


This constant was deprecated
in API level 26.
for non-system apps. Use TYPE_APPLICATION_OVERLAY instead.

int TYPE_WALLPAPER

Window type: wallpaper window, placed behind any window that wants
to sit on top of the wallpaper.

Inherited constants

From class
android.view.ViewGroup.LayoutParams

int FILL_PARENT

Special value for the height or width requested by a View.

int MATCH_PARENT

Special value for the height or width requested by a View.

int WRAP_CONTENT

Special value for the height or width requested by a View.

From interface
android.os.Parcelable

int CONTENTS_FILE_DESCRIPTOR

Descriptor bit used with describeContents(): indicates that
the Parcelable object’s flattened representation includes a file descriptor.

int PARCELABLE_WRITE_RETURN_VALUE

Flag for use with writeToParcel(Parcel, int): the object being written
is a return value, that is the result of a function such as
«Parcelable someFunction()«,
«void someFunction(out Parcelable)«, or
«void someFunction(inout Parcelable)«.

Fields


public
static
final
Creator<WindowManager.LayoutParams>
CREATOR


public

float

alpha

An alpha value to apply to this entire window.


public

float

buttonBrightness

This can be used to override the standard behavior of the button and
keyboard backlights.


public

float

dimAmount

When FLAG_DIM_BEHIND is set, this is the amount of dimming
to apply.


public

int

flags

Various behavioral options/flags.


public

int

format

The desired bitmap format.


public

int

gravity

Placement of window within the screen as per Gravity.


public

float

horizontalMargin

The horizontal margin, as a percentage of the container’s width,
between the container and the widget.


public

float

horizontalWeight

Indicates how much of the extra space will be allocated horizontally
to the view associated with these LayoutParams.


public

int

layoutInDisplayCutoutMode

Controls how the window is laid out if there is a DisplayCutout.


public

int

memoryType


This field was deprecated
in API level 15.
this is ignored


public

String

packageName

Name of the package owning this window.


public

boolean

preferMinimalPostProcessing

Indicates whether this window wants the connected display to do minimal post processing
on the produced image or video frames.


public

int

preferredDisplayModeId

Id of the preferred display mode for the window.


public

float

preferredRefreshRate

The preferred refresh rate for the window.


public

int

rotationAnimation

Define the exit and entry animations used on this window when the device is rotated.


public

float

screenBrightness

This can be used to override the user’s preferred brightness of
the screen.


public

int

screenOrientation

Specific orientation value for a window.


public

int

softInputMode

Desired operating mode for any soft input area.


public

int

systemUiVisibility


This field was deprecated
in API level 30.
SystemUiVisibility flags are deprecated. Use WindowInsetsController
instead.


public

IBinder

token

Identifier for this window.


public

int

type

The general type of window.


public

float

verticalMargin

The vertical margin, as a percentage of the container’s height,
between the container and the widget.


public

float

verticalWeight

Indicates how much of the extra space will be allocated vertically
to the view associated with these LayoutParams.


public

int

windowAnimations

A style resource defining the animations to use for this window.


public

int

x

X position for this window.


public

int

y

Y position for this window.

Inherited fields

From class
android.view.ViewGroup.LayoutParams


public

int

height

Information about how tall the view wants to be.


public

LayoutAnimationController.AnimationParameters

layoutAnimationParameters

Used to animate layouts.


public

int

width

Information about how wide the view wants to be.

Public constructors


LayoutParams()


LayoutParams(Parcel in)


LayoutParams(int _type)


LayoutParams(int _type, int _flags)


LayoutParams(int _type, int _flags, int _format)


LayoutParams(int w, int h, int _type, int _flags, int _format)


LayoutParams(int w, int h, int xpos, int ypos, int _type, int _flags, int _format)

Public methods

boolean


areWallpaperTouchEventsEnabled()

Returns whether sending touch events to the system wallpaper (which can be provided by a
third-party application) is enabled for windows that show wallpaper in background.

boolean


canPlayMoveAnimation()

final

int


copyFrom(WindowManager.LayoutParams o)

String


debug(String output)

int


describeContents()

Describe the kinds of special objects contained in this Parcelable
instance’s marshaled representation.

int


getBlurBehindRadius()

Returns the blur behind radius of the window.

int


getColorMode()

Returns the color mode of the window, one of ActivityInfo.COLOR_MODE_DEFAULT,
ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT or ActivityInfo.COLOR_MODE_HDR.

float


getDesiredHdrHeadroom()

Get the desired amount of HDR headroom as set by setDesiredHdrHeadroom(float)

int


getFitInsetsSides()

int


getFitInsetsTypes()

boolean


getFrameRateBoostOnTouchEnabled()

Get the value whether we should enable touch boost as set
by setFrameRateBoostOnTouchEnabled(boolean)

final

CharSequence


getTitle()

boolean


isFitInsetsIgnoringVisibility()

boolean


isFrameRatePowerSavingsBalanced()

Get the value whether frameratepowersavingsbalance is enabled for this Window.

boolean


isHdrConversionEnabled()

Returns whether the HDR conversion is enabled for the window

static

boolean


mayUseInputMethod(int flags)

Given a particular set of window manager flags, determine whether
such a window may be a target for an input method when it has
focus.

void


setBlurBehindRadius(int blurBehindRadius)

Blurs the screen behind the window.

void


setCanPlayMoveAnimation(boolean enable)

Set whether animations can be played for position changes on this window.

void


setColorMode(int colorMode)

Set the color mode of the window.

void


setDesiredHdrHeadroom(float desiredHeadroom)

Sets the desired about of HDR headroom to be used when rendering as a ratio of
targetHdrPeakBrightnessInNits / targetSdrWhitePointInNits.

void


setFitInsetsIgnoringVisibility(boolean ignore)

Specifies if this window should fit the window insets no matter they are visible or not.

void


setFitInsetsSides(int sides)

Specifies sides of insets that this window should avoid overlapping during layout.

void


setFitInsetsTypes(int types)

Specifies types of insets that this window should avoid overlapping during layout.

void


setFrameRateBoostOnTouchEnabled(boolean enabled)

Set the value whether we should enable Touch Boost

void


setFrameRatePowerSavingsBalanced(boolean enabled)

Set the value whether frameratepowersavingsbalance is enabled for this Window.

void


setHdrConversionEnabled(boolean enabled)

Enables/disables the HDR conversion for the window.

final

void


setTitle(CharSequence title)

Sets a title for the window.

void


setWallpaperTouchEventsEnabled(boolean enable)

Set whether sending touch events to the system wallpaper (which can be provided by a
third-party application) should be enabled for windows that show wallpaper in
background.

String


toString()

Returns a string representation of the object.

void


writeToParcel(Parcel out, int parcelableFlags)

Flatten this object in to a Parcel.

Inherited methods

From class

android.view.ViewGroup.LayoutParams


void


resolveLayoutDirection(int layoutDirection)

Resolve layout parameters depending on the layout direction.

void


setBaseAttributes(TypedArray a, int widthAttr, int heightAttr)

Extracts the layout parameters from the supplied attributes.

From class

java.lang.Object


Object


clone()

Creates and returns a copy of this object.

boolean


equals(Object obj)

Indicates whether some other object is «equal to» this one.

void


finalize()

Called by the garbage collector on an object when garbage collection
determines that there are no more references to the object.

final

Class<?>


getClass()

Returns the runtime class of this Object.

int


hashCode()

Returns a hash code value for the object.

final

void


notify()

Wakes up a single thread that is waiting on this object’s
monitor.

final

void


notifyAll()

Wakes up all threads that are waiting on this object’s monitor.

String


toString()

Returns a string representation of the object.

final

void


wait(long timeoutMillis, int nanos)

Causes the current thread to wait until it is awakened, typically
by being notified or interrupted, or until a
certain amount of real time has elapsed.

final

void


wait(long timeoutMillis)

Causes the current thread to wait until it is awakened, typically
by being notified or interrupted, or until a
certain amount of real time has elapsed.

final

void


wait()

Causes the current thread to wait until it is awakened, typically
by being notified or interrupted.

From interface

android.os.Parcelable



abstract

int


describeContents()

Describe the kinds of special objects contained in this Parcelable
instance’s marshaled representation.


abstract

void


writeToParcel(Parcel dest, int flags)

Flatten this object in to a Parcel.

XML attributes

android:windowNoMoveAnimation

Flag indicating whether this window should skip movement animations.
See also WindowManager.LayoutParams.setCanPlayMoveAnimation(boolean)

May be a boolean value, such as «true» or
«false«.

Related methods:

  • setCanPlayMoveAnimation(boolean)

Constants

ALPHA_CHANGED

public static final int ALPHA_CHANGED

Constant Value:

128
(0x00000080)

ANIMATION_CHANGED

public static final int ANIMATION_CHANGED

Constant Value:

16
(0x00000010)

BRIGHTNESS_OVERRIDE_FULL

public static final float BRIGHTNESS_OVERRIDE_FULL

Value for screenBrightness and buttonBrightness
indicating that the screen or button backlight brightness should be set
to the hightest value when this window is in front.

Constant Value:

1.0

BRIGHTNESS_OVERRIDE_NONE

public static final float BRIGHTNESS_OVERRIDE_NONE

Default value for screenBrightness and buttonBrightness
indicating that the brightness value is not overridden for this window
and normal brightness policy should be used.

Constant Value:

-1.0

BRIGHTNESS_OVERRIDE_OFF

public static final float BRIGHTNESS_OVERRIDE_OFF

Value for screenBrightness and buttonBrightness
indicating that the screen or button backlight brightness should be set
to the lowest value when this window is in front.

Constant Value:

0.0

DIM_AMOUNT_CHANGED

public static final int DIM_AMOUNT_CHANGED

Constant Value:

32
(0x00000020)

DISPLAY_FLAG_DISABLE_HDR_CONVERSION

public static final int DISPLAY_FLAG_DISABLE_HDR_CONVERSION

Indicates whether this window wants the HDR conversion is disabled.

Constant Value:

1
(0x00000001)

FIRST_APPLICATION_WINDOW

public static final int FIRST_APPLICATION_WINDOW

Start of window types that represent normal application windows.

Constant Value:

1
(0x00000001)

FIRST_SUB_WINDOW

public static final int FIRST_SUB_WINDOW

Start of types of sub-windows. The token of these windows
must be set to the window they are attached to. These types of
windows are kept next to their attached window in Z-order, and their
coordinate space is relative to their attached window.

Constant Value:

1000
(0x000003e8)

FIRST_SYSTEM_WINDOW

public static final int FIRST_SYSTEM_WINDOW

Start of system-specific window types. These are not normally
created by applications.

Constant Value:

2000
(0x000007d0)

FLAGS_CHANGED

public static final int FLAGS_CHANGED

Constant Value:

4
(0x00000004)

FLAG_ALLOW_LOCK_WHILE_SCREEN_ON

public static final int FLAG_ALLOW_LOCK_WHILE_SCREEN_ON

Window flag: as long as this window is visible to the user, allow
the lock screen to activate while the screen is on.
This can be used independently, or in combination with
FLAG_KEEP_SCREEN_ON and/or FLAG_SHOW_WHEN_LOCKED

Constant Value:

1
(0x00000001)

FLAG_ALT_FOCUSABLE_IM

public static final int FLAG_ALT_FOCUSABLE_IM

Window flag: when set, inverts the input method focusability of the window.

The effect of setting this flag depends on whether FLAG_NOT_FOCUSABLE is set:

If FLAG_NOT_FOCUSABLE is not set, i.e. when the window is focusable,
setting this flag prevents this window from becoming the target of the input method.
Consequently, it will not be able to interact with the input method,
and will be layered above the input method (unless there is another input method
target above it).

If FLAG_NOT_FOCUSABLE is set, setting this flag requests for the window
to be the input method target even though the window is not focusable.
Consequently, it will be layered below the input method.
Note: Windows that set FLAG_NOT_FOCUSABLE cannot interact with the input method,
regardless of this flag.

Constant Value:

131072
(0x00020000)

FLAG_BLUR_BEHIND

public static final int FLAG_BLUR_BEHIND

Window flag: enable blur behind for this window.

Constant Value:

4
(0x00000004)

FLAG_DIM_BEHIND

public static final int FLAG_DIM_BEHIND

Window flag: everything behind this window will be dimmed.
Use dimAmount to control the amount of dim.

Constant Value:

2
(0x00000002)

FLAG_DISMISS_KEYGUARD

public static final int FLAG_DISMISS_KEYGUARD


This constant was deprecated
in API level 26.

Use FLAG_SHOW_WHEN_LOCKED or
KeyguardManager.requestDismissKeyguard instead.
Since keyguard was dismissed all the time as long as an
activity with this flag on its window was focused,
keyguard couldn’t guard against unintentional touches on
the screen, which isn’t desired.

Window flag: when set the window will cause the keyguard to be
dismissed, only if it is not a secure lock keyguard. Because such a
keyguard is not needed for security, it will never re-appear if the
user navigates to another window (in contrast to
FLAG_SHOW_WHEN_LOCKED, which will only temporarily hide both
secure and non-secure keyguards but ensure they reappear when the
user moves to another UI that doesn’t hide them). If the keyguard is
currently active and is secure (requires an unlock credential) than
the user will still need to confirm it before seeing this window,
unless FLAG_SHOW_WHEN_LOCKED has also been set.

Constant Value:

4194304
(0x00400000)

FLAG_DITHER

public static final int FLAG_DITHER


This constant was deprecated
in API level 17.

This flag is no longer used.

Window flag: turn on dithering when compositing this window to
the screen.

Constant Value:

4096
(0x00001000)

FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS

public static final int FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS

Flag indicating that this Window is responsible for drawing the background for the
system bars. If set, the system bars are drawn with a transparent background and the
corresponding areas in this window are filled with the colors specified in
Window.getStatusBarColor() and Window.getNavigationBarColor().

Constant Value:

-2147483648
(0x80000000)

FLAG_FORCE_NOT_FULLSCREEN

public static final int FLAG_FORCE_NOT_FULLSCREEN


This constant was deprecated
in API level 30.

This value became API «by accident», and shouldn’t be used by 3rd party
applications.

Window flag: override FLAG_FULLSCREEN and force the
screen decorations (such as the status bar) to be shown.

Constant Value:

2048
(0x00000800)

FLAG_HARDWARE_ACCELERATED

public static final int FLAG_HARDWARE_ACCELERATED

Indicates whether this window should be hardware accelerated.
Requesting hardware acceleration does not guarantee it will happen.

This flag can be controlled programmatically only to enable
hardware acceleration. To enable hardware acceleration for a given
window programmatically, do the following:

 Window w = activity.getWindow(); // in Activity's onCreate() for instance
 w.setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
         WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
 

It is important to remember that this flag must
be set before setting the content view of your activity or dialog.

This flag cannot be used to disable hardware acceleration after it
was enabled in your manifest using
R.attr.hardwareAccelerated. If you need to selectively
and programmatically disable hardware acceleration (for automated testing
for instance), make sure it is turned off in your manifest and enable it
on your activity or dialog when you need it instead, using the method
described above.

This flag is automatically set by the system if the
android:hardwareAccelerated
XML attribute is set to true on an activity or on the application.

Constant Value:

16777216
(0x01000000)

FLAG_IGNORE_CHEEK_PRESSES

public static final int FLAG_IGNORE_CHEEK_PRESSES

Window flag: intended for windows that will often be used when the user is
holding the screen against their face, it will aggressively filter the event
stream to prevent unintended presses in this situation that may not be
desired for a particular window, when such an event stream is detected, the
application will receive a CANCEL motion event to indicate this so applications
can handle this accordingly by taking no action on the event
until the finger is released.

Constant Value:

32768
(0x00008000)

FLAG_KEEP_SCREEN_ON

public static final int FLAG_KEEP_SCREEN_ON

Window flag: as long as this window is visible to the user, keep
the device’s screen turned on and bright.

Constant Value:

128
(0x00000080)

FLAG_LAYOUT_ATTACHED_IN_DECOR

public static final int FLAG_LAYOUT_ATTACHED_IN_DECOR


This constant was deprecated
in API level 30.

Use setFitInsetsTypes(int) to determine whether the attached
window will overlap with system bars.

Window flag: When requesting layout with an attached window, the attached window may
overlap with the screen decorations of the parent window such as the navigation bar. By
including this flag, the window manager will layout the attached window within the decor
frame of the parent window such that it doesn’t overlap with screen decorations.

Constant Value:

1073741824
(0x40000000)

FLAG_LAYOUT_INSET_DECOR

public static final int FLAG_LAYOUT_INSET_DECOR


This constant was deprecated
in API level 30.

Insets will always be delivered to your application.

Window flag: a special option only for use in combination with
FLAG_LAYOUT_IN_SCREEN. When requesting layout in the
screen your window may appear on top of or behind screen decorations
such as the status bar. By also including this flag, the window
manager will report the inset rectangle needed to ensure your
content is not covered by screen decorations. This flag is normally
set for you by Window as described in Window.setFlags

Constant Value:

65536
(0x00010000)

FLAG_LAYOUT_IN_OVERSCAN

public static final int FLAG_LAYOUT_IN_OVERSCAN


This constant was deprecated
in API level 30.

Overscan areas aren’t set by any Android product anymore as of Android 11.

Window flag: allow window contents to extend in to the screen’s
overscan area, if there is one. The window should still correctly
position its contents to take the overscan area into account.

This flag can be controlled in your theme through the
R.attr.windowOverscan attribute; this attribute
is automatically set for you in the standard overscan themes
such as
R.style.Theme_Holo_NoActionBar_Overscan,
R.style.Theme_Holo_Light_NoActionBar_Overscan,
R.style.Theme_DeviceDefault_NoActionBar_Overscan, and
R.style.Theme_DeviceDefault_Light_NoActionBar_Overscan.

When this flag is enabled for a window, its normal content may be obscured
to some degree by the overscan region of the display. To ensure key parts of
that content are visible to the user, you can use
View.setFitsSystemWindows(boolean)
to set the point in the view hierarchy where the appropriate offsets should
be applied. (This can be done either by directly calling this function, using
the R.attr.fitsSystemWindows attribute in your view hierarchy,
or implementing you own View.fitSystemWindows(Rect) method).

This mechanism for positioning content elements is identical to its equivalent
use with layout and View.setSystemUiVisibility(int); here is an example layout that will correctly
position its UI elements with this overscan flag is set:

<!-- This layout is designed for use with FLAG_LAYOUT_IN_OVERSCAN, so its window will
     be placed into the overscan region of the display (if there is one).  Thus the contents
     of the top-level view may be obscured around the edges by the display, leaving the
     edge of the box background used here invisible. -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/box_white">

    <!-- This is still in the same position as the top-level FrameLayout, so the contentx
        of this TextView may also be obscured. -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="3dp"
        android:layout_marginLeft="3dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Overscan" />

    <!-- This FrameLayout uses android:fitsSystemWindows to have its padding adjusted so
         that within that space its content is offset to not be obscured by the overscan
         region (or also system decors that are covering its UI. -->
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <!-- Now that we are within the padding region of the parent FrameLayout, we can
             safely place content that will be visible to the user. -->
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/frantic"
            android:scaleType="fitXY" />
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/box_white" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp"
            android:layout_marginLeft="3dp"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Content" />

    </FrameLayout>

</FrameLayout>

Constant Value:

33554432
(0x02000000)

FLAG_LAYOUT_IN_SCREEN

public static final int FLAG_LAYOUT_IN_SCREEN

Window flag for attached windows: Place the window within the entire screen, ignoring
any constraints from the parent window.

Note: on displays that have a DisplayCutout, the window may be placed
such that it avoids the DisplayCutout area if necessary according to the
layoutInDisplayCutoutMode.

Constant Value:

256
(0x00000100)

FLAG_LAYOUT_NO_LIMITS

public static final int FLAG_LAYOUT_NO_LIMITS

Window flag: allow window to extend outside of the screen.

Constant Value:

512
(0x00000200)

FLAG_LOCAL_FOCUS_MODE

public static final int FLAG_LOCAL_FOCUS_MODE

Flag for a window in local focus mode.
Window in local focus mode can control focus independent of window manager using
Window.setLocalFocus(boolean, boolean).
Usually window in this mode will not get touch/key events from window manager, but will
get events only via local injection using Window.injectInputEvent(InputEvent).

Constant Value:

268435456
(0x10000000)

FLAG_NOT_FOCUSABLE

public static final int FLAG_NOT_FOCUSABLE

Window flag: this window won’t ever get key input focus, so the
user can not send key or other button events to it. Those will
instead go to whatever focusable window is behind it. This flag
will also enable FLAG_NOT_TOUCH_MODAL whether or not that
is explicitly set.

Setting this flag also implies that the window will not need to
interact with
a soft input method, so it will be Z-ordered and positioned
independently of any active input method (typically this means it
gets Z-ordered on top of the input method, so it can use the full
screen for its content and cover the input method if needed. You
can use FLAG_ALT_FOCUSABLE_IM to modify this behavior.

Constant Value:

8
(0x00000008)

FLAG_NOT_TOUCHABLE

public static final int FLAG_NOT_TOUCHABLE

Window flag: this window can never receive touch events.

The intention of this flag is to leave the touch to be handled by some window below
this window (in Z order).

Starting from Android Build.VERSION_CODES.S, for security reasons, touch
events that pass through windows containing this flag (ie. are within the bounds of the
window) will only be delivered to the touch-consuming window if one (or more) of the
items below are true:

  1. Same UID: This window belongs to the same UID that owns the touch-consuming
    window.
  2. Trusted windows: This window is trusted. Trusted windows include (but are
    not limited to) accessibility windows (TYPE_ACCESSIBILITY_OVERLAY), the IME
    (TYPE_INPUT_METHOD) and assistant windows (TYPE_VOICE_INTERACTION). Windows of
    type TYPE_APPLICATION_OVERLAY are not trusted, see below.
  3. Invisible windows: This window is View.GONE or
    View.INVISIBLE.
  4. Fully transparent windows: This window has LayoutParams.alpha equal
    to 0.
  5. One SAW window with enough transparency: This window is of type TYPE_APPLICATION_OVERLAY, has LayoutParams.alpha below or equal to the
    maximum obscuring opacity (see below) and it’s the
    only window of type TYPE_APPLICATION_OVERLAY from this UID in the touch
    path.
  6. Multiple SAW windows with enough transparency: The multiple overlapping
    TYPE_APPLICATION_OVERLAY windows in the
    touch path from this UID have a combined obscuring opacity below or equal to
    the maximum obscuring opacity. See section
    Combined obscuring opacity below on how to compute this
    value.

If none of these cases hold, the touch will not be delivered and a message will be
logged to logcat.

Maximum obscuring opacity

This value is 0.8. Apps that want to gather this value from the system rather
than hard-coding it might want to use InputManager.getMaximumObscuringOpacityForTouch().

Combined obscuring opacity

The combined obscuring opacity of a set of windows is obtained by combining the
opacity values of all windows in the set using the associative and commutative operation
defined as:

 opacity({A,B}) = 1 - (1 - opacity(A))*(1 - opacity(B))
 

where opacity(X) is the LayoutParams.alpha of window X. So, for a set
of windows {W1, .., Wn}, the combined obscuring opacity will be:

 opacity({W1, .., Wn}) = 1 - (1 - opacity(W1)) * ... * (1 - opacity(Wn))
 

Constant Value:

16
(0x00000010)

FLAG_NOT_TOUCH_MODAL

public static final int FLAG_NOT_TOUCH_MODAL

Window flag: even when this window is focusable (its
FLAG_NOT_FOCUSABLE is not set), allow any pointer events
outside of the window to be sent to the windows behind it. Otherwise
it will consume all pointer events itself, regardless of whether they
are inside of the window.

Constant Value:

32
(0x00000020)

FLAG_SCALED

public static final int FLAG_SCALED

Window flag: a special mode where the layout parameters are used
to perform scaling of the surface when it is composited to the
screen.

Constant Value:

16384
(0x00004000)

FLAG_SECURE

public static final int FLAG_SECURE

Window flag: treat the content of the window as secure, preventing
it from appearing in screenshots or from being viewed on non-secure
displays.

See View.setContentSensitivity(int), a window hosting
a sensitive view will be marked as secure during media projection, preventing
it from being viewed on non-secure displays and during screen share.

See Display.FLAG_SECURE for more details about
secure surfaces and secure displays.

Constant Value:

8192
(0x00002000)

FLAG_SHOW_WALLPAPER

public static final int FLAG_SHOW_WALLPAPER

Window flag: ask that the system wallpaper be shown behind
your window. The window surface must be translucent to be able
to actually see the wallpaper behind it; this flag just ensures
that the wallpaper surface will be there if this window actually
has translucent regions.

This flag can be controlled in your theme through the
R.attr.windowShowWallpaper attribute; this attribute
is automatically set for you in the standard wallpaper themes
such as R.style.Theme_Wallpaper,
R.style.Theme_Wallpaper_NoTitleBar,
R.style.Theme_Wallpaper_NoTitleBar_Fullscreen,
R.style.Theme_Holo_Wallpaper,
R.style.Theme_Holo_Wallpaper_NoTitleBar,
R.style.Theme_DeviceDefault_Wallpaper, and
R.style.Theme_DeviceDefault_Wallpaper_NoTitleBar.

When this flag is set, all touch events sent to this window is also sent to the
wallpaper, which is used to interact with live wallpapers. Check
LayoutParams.areWallpaperTouchEventsEnabled(), which is set to true
by default. When showing sensitive information on the window, if you want to disable
sending the touch events to the wallpaper, use
LayoutParams.setWallpaperTouchEventsEnabled(boolean).

Constant Value:

1048576
(0x00100000)

FLAG_SHOW_WHEN_LOCKED

public static final int FLAG_SHOW_WHEN_LOCKED


This constant was deprecated
in API level 27.

Use R.attr.showWhenLocked or
Activity.setShowWhenLocked(boolean) instead to prevent an
unintentional double life-cycle event.

Window flag: special flag to let windows be shown when the screen
is locked. This will let application windows take precedence over
key guard or any other lock screens. Can be used with
FLAG_KEEP_SCREEN_ON to turn screen on and display windows
directly before showing the key guard window. Can be used with
FLAG_DISMISS_KEYGUARD to automatically fully dismisss
non-secure keyguards. This flag only applies to the top-most
full-screen window.

Constant Value:

524288
(0x00080000)

FLAG_SPLIT_TOUCH

public static final int FLAG_SPLIT_TOUCH

Window flag: when set the window will accept for touch events
outside of its bounds to be sent to other windows that also
support split touch. When this flag is not set, the first pointer
that goes down determines the window to which all subsequent touches
go until all pointers go up. When this flag is set, each pointer
(not necessarily the first) that goes down determines the window
to which all subsequent touches of that pointer will go until that
pointer goes up thereby enabling touches with multiple pointers
to be split across multiple windows.

Constant Value:

8388608
(0x00800000)

FLAG_TOUCHABLE_WHEN_WAKING

public static final int FLAG_TOUCHABLE_WHEN_WAKING


This constant was deprecated
in API level 20.

This flag has no effect.

Window flag: when set, if the device is asleep when the touch
screen is pressed, you will receive this first touch event. Usually
the first touch event is consumed by the system since the user can
not see what they are pressing on.

Constant Value:

64
(0x00000040)

FLAG_TURN_SCREEN_ON

public static final int FLAG_TURN_SCREEN_ON


This constant was deprecated
in API level 27.

Use R.attr.turnScreenOn or
Activity.setTurnScreenOn(boolean) instead to prevent an
unintentional double life-cycle event.

Window flag: when set as a window is being added or made
visible, once the window has been shown then the system will
poke the power manager’s user activity (as if the user had woken
up the device) to turn the screen on.

Constant Value:

2097152
(0x00200000)

FLAG_WATCH_OUTSIDE_TOUCH

public static final int FLAG_WATCH_OUTSIDE_TOUCH

Window flag: if you have set FLAG_NOT_TOUCH_MODAL, you
can set this flag to receive a single special MotionEvent with
the action
MotionEvent.ACTION_OUTSIDE for
touches that occur outside of your window. Note that you will not
receive the full down/move/up gesture, only the location of the
first down as an ACTION_OUTSIDE.

Constant Value:

262144
(0x00040000)

FORMAT_CHANGED

public static final int FORMAT_CHANGED

Constant Value:

8
(0x00000008)

LAST_APPLICATION_WINDOW

public static final int LAST_APPLICATION_WINDOW

End of types of application windows.

Constant Value:

99
(0x00000063)

LAST_SUB_WINDOW

public static final int LAST_SUB_WINDOW

End of types of sub-windows.

Constant Value:

1999
(0x000007cf)

LAST_SYSTEM_WINDOW

public static final int LAST_SYSTEM_WINDOW

End of types of system windows.

Constant Value:

2999
(0x00000bb7)

LAYOUT_CHANGED

public static final int LAYOUT_CHANGED

Constant Value:

1
(0x00000001)

LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT

public static final int LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT

The window is allowed to extend into the DisplayCutout area, only if the
DisplayCutout is fully contained within a system bar or the DisplayCutout
is not deeper than 16 dp, but this depends on the OEM choice. Otherwise, the window is
laid out such that it does not overlap with the DisplayCutout area.

In practice, this means that if the window did not set FLAG_FULLSCREEN or
View.SYSTEM_UI_FLAG_FULLSCREEN, it can extend into the cutout area in portrait
if the cutout is at the top edge. Similarly for
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION and a cutout at the bottom of the screen.
Otherwise (i.e. fullscreen or landscape) it is laid out such that it does not overlap the
cutout area.

The usual precautions for not overlapping with the status and navigation bar are
sufficient for ensuring that no important content overlaps with the DisplayCutout.

Note: OEMs can have an option to allow the window to always extend into the
DisplayCutout area, no matter the cutout flag set, when the DisplayCutout
is on the different side from system bars, only if the DisplayCutout overlaps at
most 16dp with the windows.
In such case, OEMs must provide an opt-in/out affordance for users.

Constant Value:

0
(0x00000000)

LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER

public static final int LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER

The window is never allowed to overlap with the DisplayCutout area.

This should be used with windows that transiently set
View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
to avoid a relayout of the window when the respective flag is set or cleared.

Constant Value:

2
(0x00000002)

LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES

public static final int LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES

The window is always allowed to extend into the DisplayCutout areas on the short
edges of the screen.

The window will never extend into a DisplayCutout area on the long edges of the
screen, unless the DisplayCutout is not deeper than 16 dp, but this depends on
the OEM choice.

Note: OEMs can have an option to allow the window to extend into the
DisplayCutout area on the long edge side, only if the cutout overlaps at most
16dp with the windows. In such case, OEMs must provide an opt-in/out affordance for
users.

The window must make sure that no important content overlaps with the
DisplayCutout.

In this mode, the window extends under cutouts on the short edge of the display in both
portrait and landscape, regardless of whether the window is hiding the system bars:

Screenshot of a fullscreen activity on a display with a cutout at the top edge in
         portrait, no letterbox is applied.

Screenshot of an activity on a display with a cutout at the top edge in landscape,
         no letterbox is applied.

A cutout in the corner can be considered to be on different edge in different device
rotations. This behavior may vary from device to device. Use this flag is possible to
letterbox your app if the display cutout is at corner.

On the other hand, should the cutout be on the long edge of the display, a letterbox will
be applied such that the window does not extend into the cutout on either long edge:

Screenshot of an activity on a display with a cutout on the long edge in portrait,
         letterbox is applied.

Note: Android might not allow the content view to overlap the system bars in view level.
To override this behavior and allow content to be able to extend into the cutout area,
call Window.setDecorFitsSystemWindows(boolean) with false.

See also:

  • DisplayCutout
  • WindowInsets.getDisplayCutout()
  • layoutInDisplayCutoutMode
  • android:windowLayoutInDisplayCutoutMode

Constant Value:

1
(0x00000001)

MEMORY_TYPE_CHANGED

public static final int MEMORY_TYPE_CHANGED

Constant Value:

256
(0x00000100)

MEMORY_TYPE_GPU

public static final int MEMORY_TYPE_GPU


This constant was deprecated
in API level 15.

this is ignored, this value is set automatically when needed.

Constant Value:

2
(0x00000002)

MEMORY_TYPE_HARDWARE

public static final int MEMORY_TYPE_HARDWARE


This constant was deprecated
in API level 15.

this is ignored, this value is set automatically when needed.

Constant Value:

1
(0x00000001)

MEMORY_TYPE_NORMAL

public static final int MEMORY_TYPE_NORMAL


This constant was deprecated
in API level 15.

this is ignored, this value is set automatically when needed.

Constant Value:

0
(0x00000000)

MEMORY_TYPE_PUSH_BUFFERS

public static final int MEMORY_TYPE_PUSH_BUFFERS


This constant was deprecated
in API level 15.

this is ignored, this value is set automatically when needed.

Constant Value:

3
(0x00000003)

ROTATION_ANIMATION_CHANGED

public static final int ROTATION_ANIMATION_CHANGED

Constant Value:

4096
(0x00001000)

ROTATION_ANIMATION_CROSSFADE

public static final int ROTATION_ANIMATION_CROSSFADE

Value for rotationAnimation which specifies that this
window will fade in or out following a rotation.

Constant Value:

1
(0x00000001)

ROTATION_ANIMATION_JUMPCUT

public static final int ROTATION_ANIMATION_JUMPCUT

Value for rotationAnimation which specifies that this window
will immediately disappear or appear following a rotation.

Constant Value:

2
(0x00000002)

ROTATION_ANIMATION_ROTATE

public static final int ROTATION_ANIMATION_ROTATE

Value for rotationAnimation which specifies that this
window will visually rotate in or out following a rotation.

Constant Value:

0
(0x00000000)

ROTATION_ANIMATION_SEAMLESS

public static final int ROTATION_ANIMATION_SEAMLESS

Value for rotationAnimation to specify seamless rotation mode.
This works like JUMPCUT but will fall back to CROSSFADE if rotation
can’t be applied without pausing the screen. For example, this is ideal
for Camera apps which don’t want the viewfinder contents to ever rotate
or fade (and rather to be seamless) but also don’t want ROTATION_ANIMATION_JUMPCUT
during app transition scenarios where seamless rotation can’t be applied.

Constant Value:

3
(0x00000003)

SCREEN_BRIGHTNESS_CHANGED

public static final int SCREEN_BRIGHTNESS_CHANGED

Constant Value:

2048
(0x00000800)

SCREEN_ORIENTATION_CHANGED

public static final int SCREEN_ORIENTATION_CHANGED

Constant Value:

1024
(0x00000400)

SOFT_INPUT_ADJUST_NOTHING

public static final int SOFT_INPUT_ADJUST_NOTHING

Adjustment option for softInputMode: set to have a window
not adjust for a shown input method. The window will not be resized,
and it will not be panned to make its focus visible.

Constant Value:

48
(0x00000030)

SOFT_INPUT_ADJUST_PAN

public static final int SOFT_INPUT_ADJUST_PAN

Adjustment option for softInputMode: set to have a window
pan when an input method is
shown, so it doesn’t need to deal with resizing but just panned
by the framework to ensure the current input focus is visible. This
can not be combined with SOFT_INPUT_ADJUST_RESIZE; if
neither of these are set, then the system will try to pick one or
the other depending on the contents of the window.

Constant Value:

32
(0x00000020)

SOFT_INPUT_ADJUST_RESIZE

public static final int SOFT_INPUT_ADJUST_RESIZE


This constant was deprecated
in API level 30.

Call Window.setDecorFitsSystemWindows(boolean) with false and
install an OnApplyWindowInsetsListener on your root content view that fits insets
of type Type.ime().

Adjustment option for softInputMode: set to allow the
window to be resized when an input
method is shown, so that its contents are not covered by the input
method. This can not be combined with
SOFT_INPUT_ADJUST_PAN; if
neither of these are set, then the system will try to pick one or
the other depending on the contents of the window. If the window’s
layout parameter flags include FLAG_FULLSCREEN, this
value for softInputMode will be ignored; the window will
not resize, but will stay fullscreen.

Constant Value:

16
(0x00000010)

SOFT_INPUT_ADJUST_UNSPECIFIED

public static final int SOFT_INPUT_ADJUST_UNSPECIFIED

Adjustment option for softInputMode: nothing specified.
The system will try to pick one or
the other depending on the contents of the window.

Constant Value:

0
(0x00000000)

SOFT_INPUT_IS_FORWARD_NAVIGATION

public static final int SOFT_INPUT_IS_FORWARD_NAVIGATION

Bit for softInputMode: set when the user has navigated
forward to the window. This is normally set automatically for
you by the system, though you may want to set it in certain cases
when you are displaying a window yourself. This flag will always
be cleared automatically after the window is displayed.

Constant Value:

256
(0x00000100)

SOFT_INPUT_MASK_ADJUST

public static final int SOFT_INPUT_MASK_ADJUST

Mask for softInputMode of the bits that determine the
way that the window should be adjusted to accommodate the soft
input window.

Constant Value:

240
(0x000000f0)

SOFT_INPUT_MASK_STATE

public static final int SOFT_INPUT_MASK_STATE

Mask for softInputMode of the bits that determine the
desired visibility state of the soft input area for this window.

Constant Value:

15
(0x0000000f)

SOFT_INPUT_MODE_CHANGED

public static final int SOFT_INPUT_MODE_CHANGED

Constant Value:

512
(0x00000200)

SOFT_INPUT_STATE_ALWAYS_HIDDEN

public static final int SOFT_INPUT_STATE_ALWAYS_HIDDEN

Visibility state for softInputMode: please always hide any
soft input area when this window receives focus.

Constant Value:

3
(0x00000003)

SOFT_INPUT_STATE_ALWAYS_VISIBLE

public static final int SOFT_INPUT_STATE_ALWAYS_VISIBLE

Visibility state for softInputMode: please always make the
soft input area visible when this window receives input focus.

Applications that target Build.VERSION_CODES.P and later, this flag
is ignored unless there is a focused view that returns true from
View.onCheckIsTextEditor() when the window is focused.

Constant Value:

5
(0x00000005)

SOFT_INPUT_STATE_HIDDEN

public static final int SOFT_INPUT_STATE_HIDDEN

Visibility state for softInputMode: please hide any soft input
area when normally appropriate (when the user is navigating
forward to your window).

Constant Value:

2
(0x00000002)

SOFT_INPUT_STATE_UNCHANGED

public static final int SOFT_INPUT_STATE_UNCHANGED

Visibility state for softInputMode: please don’t change the state of
the soft input area.

Constant Value:

1
(0x00000001)

SOFT_INPUT_STATE_UNSPECIFIED

public static final int SOFT_INPUT_STATE_UNSPECIFIED

Visibility state for softInputMode: no state has been specified. The system may
show or hide the software keyboard for better user experience when the window gains
focus.

Constant Value:

0
(0x00000000)

SOFT_INPUT_STATE_VISIBLE

public static final int SOFT_INPUT_STATE_VISIBLE

Visibility state for softInputMode: please show the soft
input area when normally appropriate (when the user is navigating
forward to your window).

Applications that target Build.VERSION_CODES.P and later, this flag
is ignored unless there is a focused view that returns true from
View.onCheckIsTextEditor() when the window is focused.

Constant Value:

4
(0x00000004)

TITLE_CHANGED

public static final int TITLE_CHANGED

Constant Value:

64
(0x00000040)

TYPE_ACCESSIBILITY_OVERLAY

public static final int TYPE_ACCESSIBILITY_OVERLAY

Window type: Windows that are overlaid only by a connected AccessibilityService for interception of
user interactions without changing the windows an accessibility service
can introspect. In particular, an accessibility service can introspect
only windows that a sighted user can interact with which is they can touch
these windows or can type into these windows. For example, if there
is a full screen accessibility overlay that is touchable, the windows
below it will be introspectable by an accessibility service even though
they are covered by a touchable window.

Constant Value:

2032
(0x000007f0)

TYPE_APPLICATION

public static final int TYPE_APPLICATION

Window type: a normal application window. The token must be
an Activity token identifying who the window belongs to.
In multiuser systems shows only on the owning user’s window.

Constant Value:

2
(0x00000002)

TYPE_APPLICATION_ATTACHED_DIALOG

public static final int TYPE_APPLICATION_ATTACHED_DIALOG

Window type: like TYPE_APPLICATION_PANEL, but layout
of the window happens as that of a top-level window, not
as a child of its container.

Constant Value:

1003
(0x000003eb)

TYPE_APPLICATION_MEDIA

public static final int TYPE_APPLICATION_MEDIA

Window type: window for showing media (such as video). These windows
are displayed behind their attached window.

Constant Value:

1001
(0x000003e9)

TYPE_APPLICATION_OVERLAY

public static final int TYPE_APPLICATION_OVERLAY

Window type: Application overlay windows are displayed above all activity windows
(types between FIRST_APPLICATION_WINDOW and LAST_APPLICATION_WINDOW)
but below critical system windows like the status bar or IME.

The system may change the position, size, or visibility of these windows at anytime
to reduce visual clutter to the user and also manage resources.

Requires Manifest.permission.SYSTEM_ALERT_WINDOW permission.

The system will adjust the importance of processes with this window type to reduce the
chance of the low-memory-killer killing them.

In multi-user systems shows only on the owning user’s screen.

Constant Value:

2038
(0x000007f6)

TYPE_APPLICATION_PANEL

public static final int TYPE_APPLICATION_PANEL

Window type: a panel on top of an application window. These windows
appear on top of their attached window.

Constant Value:

1000
(0x000003e8)

TYPE_APPLICATION_STARTING

public static final int TYPE_APPLICATION_STARTING

Window type: special application window that is displayed while the
application is starting. Not for use by applications themselves;
this is used by the system to display something until the
application can show its own windows.
In multiuser systems shows on all users’ windows.

Constant Value:

3
(0x00000003)

TYPE_APPLICATION_SUB_PANEL

public static final int TYPE_APPLICATION_SUB_PANEL

Window type: a sub-panel on top of an application window. These
windows are displayed on top their attached window and any
TYPE_APPLICATION_PANEL panels.

Constant Value:

1002
(0x000003ea)

TYPE_BASE_APPLICATION

public static final int TYPE_BASE_APPLICATION

Window type: an application window that serves as the «base» window
of the overall application; all other application windows will
appear on top of it.
In multiuser systems shows only on the owning user’s window.

Constant Value:

1
(0x00000001)

TYPE_CHANGED

public static final int TYPE_CHANGED

Constant Value:

2
(0x00000002)

TYPE_DRAWN_APPLICATION

public static final int TYPE_DRAWN_APPLICATION

Window type: a variation on TYPE_APPLICATION that ensures the window
manager will wait for this window to be drawn before the app is shown.
In multiuser systems shows only on the owning user’s window.

Constant Value:

4
(0x00000004)

TYPE_INPUT_METHOD

public static final int TYPE_INPUT_METHOD

Window type: internal input methods windows, which appear above
the normal UI. Application windows may be resized or panned to keep
the input focus visible while this window is displayed.
In multiuser systems shows only on the owning user’s window.

Constant Value:

2011
(0x000007db)

TYPE_INPUT_METHOD_DIALOG

public static final int TYPE_INPUT_METHOD_DIALOG

Window type: internal input methods dialog windows, which appear above
the current input method window.
In multiuser systems shows only on the owning user’s window.

Constant Value:

2012
(0x000007dc)

TYPE_KEYGUARD_DIALOG

public static final int TYPE_KEYGUARD_DIALOG

Window type: dialogs that the keyguard shows
In multiuser systems shows on all users’ windows.

Constant Value:

2009
(0x000007d9)

TYPE_PHONE

public static final int TYPE_PHONE


This constant was deprecated
in API level 26.

for non-system apps. Use TYPE_APPLICATION_OVERLAY instead.

Window type: phone. These are non-application windows providing
user interaction with the phone (in particular incoming calls).
These windows are normally placed above all applications, but behind
the status bar.
In multiuser systems shows on all users’ windows.

Constant Value:

2002
(0x000007d2)

TYPE_PRIORITY_PHONE

public static final int TYPE_PRIORITY_PHONE


This constant was deprecated
in API level 26.

for non-system apps. Use TYPE_APPLICATION_OVERLAY instead.

Window type: priority phone UI, which needs to be displayed even if
the keyguard is active. These windows must not take input
focus, or they will interfere with the keyguard.
In multiuser systems shows on all users’ windows.

Constant Value:

2007
(0x000007d7)

TYPE_PRIVATE_PRESENTATION

public static final int TYPE_PRIVATE_PRESENTATION

Window type: Window for Presentation on top of private
virtual display.

Constant Value:

2030
(0x000007ee)

TYPE_SEARCH_BAR

public static final int TYPE_SEARCH_BAR

Window type: the search bar. There can be only one search bar
window; it is placed at the top of the screen.
In multiuser systems shows on all users’ windows.

Constant Value:

2001
(0x000007d1)

TYPE_STATUS_BAR

public static final int TYPE_STATUS_BAR

Window type: the status bar. There can be only one status bar
window; it is placed at the top of the screen, and all other
windows are shifted down so they are below it.
In multiuser systems shows on all users’ windows.

Constant Value:

2000
(0x000007d0)

TYPE_SYSTEM_ALERT

public static final int TYPE_SYSTEM_ALERT


This constant was deprecated
in API level 26.

for non-system apps. Use TYPE_APPLICATION_OVERLAY instead.

Window type: system window, such as low power alert. These windows
are always on top of application windows.
In multiuser systems shows only on the owning user’s window.

Constant Value:

2003
(0x000007d3)

TYPE_SYSTEM_DIALOG

public static final int TYPE_SYSTEM_DIALOG

Window type: panel that slides out from the status bar
In multiuser systems shows on all users’ windows.

Constant Value:

2008
(0x000007d8)

TYPE_SYSTEM_ERROR

public static final int TYPE_SYSTEM_ERROR


This constant was deprecated
in API level 26.

for non-system apps. Use TYPE_APPLICATION_OVERLAY instead.

Window type: internal system error windows, appear on top of
everything they can.
In multiuser systems shows only on the owning user’s window.

Constant Value:

2010
(0x000007da)

TYPE_SYSTEM_OVERLAY

public static final int TYPE_SYSTEM_OVERLAY


This constant was deprecated
in API level 26.

for non-system apps. Use TYPE_APPLICATION_OVERLAY instead.

Window type: system overlay windows, which need to be displayed
on top of everything else. These windows must not take input
focus, or they will interfere with the keyguard.
In multiuser systems shows only on the owning user’s window.

Constant Value:

2006
(0x000007d6)

TYPE_TOAST

public static final int TYPE_TOAST


This constant was deprecated
in API level 26.

for non-system apps. Use TYPE_APPLICATION_OVERLAY instead.

Window type: transient notifications.
In multiuser systems shows only on the owning user’s window.

Constant Value:

2005
(0x000007d5)

TYPE_WALLPAPER

public static final int TYPE_WALLPAPER

Window type: wallpaper window, placed behind any window that wants
to sit on top of the wallpaper.
In multiuser systems shows only on the owning user’s window.

Constant Value:

2013
(0x000007dd)

Fields

alpha

public float alpha

An alpha value to apply to this entire window.
An alpha of 1.0 means fully opaque and 0.0 means fully transparent

buttonBrightness

public float buttonBrightness

This can be used to override the standard behavior of the button and
keyboard backlights. A value of less than 0, the default, means to
use the standard backlight behavior. 0 to 1 adjusts the brightness
from dark to full bright.

dimAmount

public float dimAmount

When FLAG_DIM_BEHIND is set, this is the amount of dimming
to apply. Range is from 1.0 for completely opaque to 0.0 for no
dim.

flags

public int flags

Various behavioral options/flags. Default is none.

Value is either 0 or a combination of FLAG_ALLOW_LOCK_WHILE_SCREEN_ON, FLAG_DIM_BEHIND, FLAG_BLUR_BEHIND, FLAG_NOT_FOCUSABLE, FLAG_NOT_TOUCHABLE, FLAG_NOT_TOUCH_MODAL, FLAG_TOUCHABLE_WHEN_WAKING, FLAG_KEEP_SCREEN_ON, FLAG_LAYOUT_IN_SCREEN, FLAG_LAYOUT_NO_LIMITS, FLAG_FULLSCREEN, FLAG_FORCE_NOT_FULLSCREEN, FLAG_DITHER, FLAG_SECURE, FLAG_SCALED, FLAG_IGNORE_CHEEK_PRESSES, FLAG_LAYOUT_INSET_DECOR, FLAG_ALT_FOCUSABLE_IM, FLAG_WATCH_OUTSIDE_TOUCH, FLAG_SHOW_WHEN_LOCKED, FLAG_SHOW_WALLPAPER, FLAG_TURN_SCREEN_ON, FLAG_DISMISS_KEYGUARD, FLAG_SPLIT_TOUCH, FLAG_HARDWARE_ACCELERATED, FLAG_LAYOUT_IN_OVERSCAN, FLAG_TRANSLUCENT_STATUS, FLAG_TRANSLUCENT_NAVIGATION, FLAG_LOCAL_FOCUS_MODE, android.view.WindowManager.LayoutParams.FLAG_SLIPPERY, FLAG_LAYOUT_ATTACHED_IN_DECOR, and FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS

See also:

  • FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
  • FLAG_DIM_BEHIND
  • FLAG_NOT_FOCUSABLE
  • FLAG_NOT_TOUCHABLE
  • FLAG_NOT_TOUCH_MODAL
  • FLAG_TOUCHABLE_WHEN_WAKING
  • FLAG_KEEP_SCREEN_ON
  • FLAG_LAYOUT_IN_SCREEN
  • FLAG_LAYOUT_NO_LIMITS
  • FLAG_FULLSCREEN
  • FLAG_FORCE_NOT_FULLSCREEN
  • FLAG_SECURE
  • FLAG_SCALED
  • FLAG_IGNORE_CHEEK_PRESSES
  • FLAG_LAYOUT_INSET_DECOR
  • FLAG_ALT_FOCUSABLE_IM
  • FLAG_WATCH_OUTSIDE_TOUCH
  • FLAG_SHOW_WHEN_LOCKED
  • FLAG_SHOW_WALLPAPER
  • FLAG_TURN_SCREEN_ON
  • FLAG_DISMISS_KEYGUARD
  • FLAG_SPLIT_TOUCH
  • FLAG_HARDWARE_ACCELERATED
  • FLAG_LOCAL_FOCUS_MODE
  • FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS

format

public int format

The desired bitmap format. May be one of the constants in
PixelFormat. The choice of format
might be overridden by setColorMode(int). Default is OPAQUE.

gravity

public int gravity

Placement of window within the screen as per Gravity. Both
Gravity.apply and
Gravity.applyDisplay are used during window layout, with this value
given as the desired gravity. For example you can specify
Gravity.DISPLAY_CLIP_HORIZONTAL and
Gravity.DISPLAY_CLIP_VERTICAL here
to control the behavior of
Gravity.applyDisplay.

Value is either 0 or a combination of Gravity.FILL, Gravity.FILL_HORIZONTAL, Gravity.FILL_VERTICAL, Gravity.START, Gravity.END, Gravity.LEFT, Gravity.RIGHT, Gravity.TOP, Gravity.BOTTOM, Gravity.CENTER, Gravity.CENTER_HORIZONTAL, Gravity.CENTER_VERTICAL, Gravity.DISPLAY_CLIP_HORIZONTAL, Gravity.DISPLAY_CLIP_VERTICAL, Gravity.CLIP_HORIZONTAL, Gravity.CLIP_VERTICAL, and Gravity.NO_GRAVITY

horizontalMargin

public float horizontalMargin

The horizontal margin, as a percentage of the container’s width,
between the container and the widget. See
Gravity.apply for how this is used. This
field is added with x to supply the xAdj parameter.

horizontalWeight

public float horizontalWeight

Indicates how much of the extra space will be allocated horizontally
to the view associated with these LayoutParams. Specify 0 if the view
should not be stretched. Otherwise the extra pixels will be pro-rated
among all views whose weight is greater than 0.

memoryType

public int memoryType


This field was deprecated
in API level 15.

this is ignored

packageName

public String packageName

Name of the package owning this window.

preferMinimalPostProcessing

public boolean preferMinimalPostProcessing

Indicates whether this window wants the connected display to do minimal post processing
on the produced image or video frames. This will only be requested if the window is
visible on the screen.

This setting should be used when low latency has a higher priority than image
enhancement processing (e.g. for games or video conferencing).

If the Display sink is connected via HDMI, the device will begin to send infoframes
with Auto Low Latency Mode enabled and Game Content Type. This will switch the connected
display to a minimal image processing mode (if available), which reduces latency,
improving the user experience for gaming or video conferencing applications. For more
information, see HDMI 2.1 specification.

If the Display sink has an internal connection or uses some other protocol than HDMI,
effects may be similar but implementation-defined.

The ability to switch to a mode with minimal post proessing may be disabled by a user
setting in the system settings menu. In that case, this field is ignored and the display
will remain in its current mode.

See also:

  • ActivityInfo.FLAG_PREFER_MINIMAL_POST_PROCESSING
  • Display.isMinimalPostProcessingSupported()
  • Window.setPreferMinimalPostProcessing(boolean)

preferredDisplayModeId

public int preferredDisplayModeId

Id of the preferred display mode for the window.

This must be one of the supported modes obtained for the display(s) the window is on.
A value of 0 means no preference.

preferredRefreshRate

public float preferredRefreshRate

The preferred refresh rate for the window.

Before API 34, this must be one of the supported refresh rates obtained
for the display(s) the window is on. The selected refresh rate will be
applied to the display’s default mode.

Starting API 34, this value is not limited to the supported refresh rates
obtained from the display(s) for the window: it can be any refresh rate
the window intends to run at. Any refresh rate can be provided as the
preferred window refresh rate. The OS will select the refresh rate that
best matches the preferredRefreshRate.

Setting this value is the equivalent of calling Surface.setFrameRate with (
preferred_frame_rate,
Surface.FRAME_RATE_COMPATIBILITY_DEFAULT,
Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS).
This should be used in favor of LayoutParams.preferredDisplayModeId for
applications that want to specify the refresh rate, but do not want to specify a
preference for any other displayMode properties (e.g., resolution).

This value is ignored if preferredDisplayModeId is set.

screenBrightness

public float screenBrightness

This can be used to override the user’s preferred brightness of
the screen. A value of less than 0, the default, means to use the
preferred screen brightness. 0 to 1 adjusts the brightness from
dark to full bright.

screenOrientation

public int screenOrientation

Specific orientation value for a window.
May be any of the same values allowed
for ActivityInfo.screenOrientation.
If not set, a default value of
ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
will be used.

Value is android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSET, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, ActivityInfo.SCREEN_ORIENTATION_USER, ActivityInfo.SCREEN_ORIENTATION_BEHIND, ActivityInfo.SCREEN_ORIENTATION_SENSOR, ActivityInfo.SCREEN_ORIENTATION_NOSENSOR, ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT, ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE, ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT, ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR, ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE, ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT, ActivityInfo.SCREEN_ORIENTATION_FULL_USER, or ActivityInfo.SCREEN_ORIENTATION_LOCKED

softInputMode

public int softInputMode

Desired operating mode for any soft input area. May be any combination
of:

  • One of the visibility states
    SOFT_INPUT_STATE_UNSPECIFIED, SOFT_INPUT_STATE_UNCHANGED,
    SOFT_INPUT_STATE_HIDDEN, SOFT_INPUT_STATE_ALWAYS_HIDDEN,
    SOFT_INPUT_STATE_VISIBLE, or SOFT_INPUT_STATE_ALWAYS_VISIBLE.
  • One of the adjustment options
    SOFT_INPUT_ADJUST_UNSPECIFIED, SOFT_INPUT_ADJUST_RESIZE,
    SOFT_INPUT_ADJUST_PAN, or SOFT_INPUT_ADJUST_NOTHING.

This flag can be controlled in your theme through the
R.attr.windowSoftInputMode attribute.

Value is either 0 or a combination of SOFT_INPUT_STATE_UNSPECIFIED, SOFT_INPUT_STATE_UNCHANGED, SOFT_INPUT_STATE_HIDDEN, SOFT_INPUT_STATE_ALWAYS_HIDDEN, SOFT_INPUT_STATE_VISIBLE, SOFT_INPUT_STATE_ALWAYS_VISIBLE, SOFT_INPUT_ADJUST_UNSPECIFIED, SOFT_INPUT_ADJUST_RESIZE, SOFT_INPUT_ADJUST_PAN, SOFT_INPUT_ADJUST_NOTHING, and SOFT_INPUT_IS_FORWARD_NAVIGATION

systemUiVisibility

public int systemUiVisibility


This field was deprecated
in API level 30.

SystemUiVisibility flags are deprecated. Use WindowInsetsController
instead.

Control the visibility of the status bar.

Value is either 0 or a combination of View.SYSTEM_UI_FLAG_VISIBLE, View.SYSTEM_UI_FLAG_LOW_PROFILE, View.SYSTEM_UI_FLAG_HIDE_NAVIGATION, View.SYSTEM_UI_FLAG_FULLSCREEN, View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR, View.SYSTEM_UI_FLAG_LAYOUT_STABLE, View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION, View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN, View.SYSTEM_UI_FLAG_IMMERSIVE, View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY, View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR, android.view.View.STATUS_BAR_DISABLE_EXPAND, android.view.View.STATUS_BAR_DISABLE_NOTIFICATION_ICONS, android.view.View.STATUS_BAR_DISABLE_NOTIFICATION_ALERTS, android.view.View.STATUS_BAR_DISABLE_NOTIFICATION_TICKER, android.view.View.STATUS_BAR_DISABLE_SYSTEM_INFO, android.view.View.STATUS_BAR_DISABLE_HOME, android.view.View.STATUS_BAR_DISABLE_BACK, android.view.View.STATUS_BAR_DISABLE_CLOCK, android.view.View.STATUS_BAR_DISABLE_RECENT, and android.view.View.STATUS_BAR_DISABLE_SEARCH

token

public IBinder token

Identifier for this window. This will usually be filled in for
you.

type

public int type

The general type of window. There are three main classes of
window types:

  • Application windows (ranging from
    FIRST_APPLICATION_WINDOW to
    LAST_APPLICATION_WINDOW) are normal top-level application
    windows. For these types of windows, the token must be
    set to the token of the activity they are a part of (this will
    normally be done for you if token is null).
  • Sub-windows (ranging from
    FIRST_SUB_WINDOW to
    LAST_SUB_WINDOW) are associated with another top-level
    window. For these types of windows, the token must be
    the token of the window it is attached to.
  • System windows (ranging from
    FIRST_SYSTEM_WINDOW to
    LAST_SYSTEM_WINDOW) are special types of windows for
    use by the system for specific purposes. They should not normally
    be used by applications, and a special permission is required
    to use them.

Value is TYPE_BASE_APPLICATION, TYPE_APPLICATION, TYPE_APPLICATION_STARTING, TYPE_DRAWN_APPLICATION, TYPE_APPLICATION_PANEL, TYPE_APPLICATION_MEDIA, TYPE_APPLICATION_SUB_PANEL, TYPE_APPLICATION_ATTACHED_DIALOG, android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ABOVE_SUB_PANEL, TYPE_STATUS_BAR, TYPE_SEARCH_BAR, TYPE_PHONE, TYPE_SYSTEM_ALERT, android.view.WindowManager.LayoutParams.TYPE_KEYGUARD, TYPE_TOAST, TYPE_SYSTEM_OVERLAY, TYPE_PRIORITY_PHONE, TYPE_SYSTEM_DIALOG, TYPE_KEYGUARD_DIALOG, TYPE_SYSTEM_ERROR, TYPE_INPUT_METHOD, TYPE_INPUT_METHOD_DIALOG, TYPE_WALLPAPER, android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL, android.view.WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_DRAG, android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL, android.view.WindowManager.LayoutParams.TYPE_POINTER, android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR, android.view.WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_BOOT_PROGRESS, android.view.WindowManager.LayoutParams.TYPE_INPUT_CONSUMER, android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL, android.view.WindowManager.LayoutParams.TYPE_DISPLAY_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY, TYPE_PRIVATE_PRESENTATION, android.view.WindowManager.LayoutParams.TYPE_VOICE_INTERACTION, TYPE_ACCESSIBILITY_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_VOICE_INTERACTION_STARTING, android.view.WindowManager.LayoutParams.TYPE_DOCK_DIVIDER, android.view.WindowManager.LayoutParams.TYPE_QS_DIALOG, android.view.WindowManager.LayoutParams.TYPE_SCREENSHOT, android.view.WindowManager.LayoutParams.TYPE_PRESENTATION, TYPE_APPLICATION_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_ACCESSIBILITY_MAGNIFICATION_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_NOTIFICATION_SHADE, or android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_ADDITIONAL

See also:

  • TYPE_BASE_APPLICATION
  • TYPE_APPLICATION
  • TYPE_APPLICATION_STARTING
  • TYPE_DRAWN_APPLICATION
  • TYPE_APPLICATION_PANEL
  • TYPE_APPLICATION_MEDIA
  • TYPE_APPLICATION_SUB_PANEL
  • TYPE_APPLICATION_ATTACHED_DIALOG
  • TYPE_STATUS_BAR
  • TYPE_SEARCH_BAR
  • TYPE_PHONE
  • TYPE_SYSTEM_ALERT
  • TYPE_TOAST
  • TYPE_SYSTEM_OVERLAY
  • TYPE_PRIORITY_PHONE
  • TYPE_SYSTEM_DIALOG
  • TYPE_KEYGUARD_DIALOG
  • TYPE_SYSTEM_ERROR
  • TYPE_INPUT_METHOD
  • TYPE_INPUT_METHOD_DIALOG

verticalMargin

public float verticalMargin

The vertical margin, as a percentage of the container’s height,
between the container and the widget. See
Gravity.apply for how this is used. This
field is added with y to supply the yAdj parameter.

verticalWeight

public float verticalWeight

Indicates how much of the extra space will be allocated vertically
to the view associated with these LayoutParams. Specify 0 if the view
should not be stretched. Otherwise the extra pixels will be pro-rated
among all views whose weight is greater than 0.

windowAnimations

public int windowAnimations

A style resource defining the animations to use for this window.
This must be a system resource; it can not be an application resource
because the window manager does not have access to applications.

y

public int y

Y position for this window. With the default gravity it is ignored.
When using Gravity.TOP or Gravity.BOTTOM it provides
an offset from the given edge.

Public constructors

LayoutParams

public LayoutParams ()

LayoutParams

public LayoutParams (Parcel in)
Parameters
in Parcel

LayoutParams

public LayoutParams (int _type)
Parameters
_type int

LayoutParams

public LayoutParams (int _type, 
                int _flags)
Parameters
_type int
_flags int

LayoutParams

public LayoutParams (int _type, 
                int _flags, 
                int _format)
Parameters
_type int
_flags int
_format int

LayoutParams

public LayoutParams (int w, 
                int h, 
                int _type, 
                int _flags, 
                int _format)
Parameters
w int
h int
_type int
_flags int
_format int

LayoutParams

public LayoutParams (int w, 
                int h, 
                int xpos, 
                int ypos, 
                int _type, 
                int _flags, 
                int _format)
Parameters
w int
h int
xpos int
ypos int
_type int
_flags int
_format int

Public methods

areWallpaperTouchEventsEnabled

public boolean areWallpaperTouchEventsEnabled ()

Returns whether sending touch events to the system wallpaper (which can be provided by a
third-party application) is enabled for windows that show wallpaper in background.
Check FLAG_SHOW_WALLPAPER for more
information on showing system wallpaper behind the window.

Returns
boolean whether sending touch events to the system wallpaper is enabled.

canPlayMoveAnimation

public boolean canPlayMoveAnimation ()

Related XML Attributes:

  • android:windowNoMoveAnimation
Returns
boolean whether playing an animation during a position change is allowed on this window.
This does not guarantee that an animation will be played in all such situations. For
example, drag-resizing may move the window but not play an animation.

describeContents

public int describeContents ()

Describe the kinds of special objects contained in this Parcelable
instance’s marshaled representation. For example, if the object will
include a file descriptor in the output of writeToParcel(android.os.Parcel, int),
the return value of this method must include the
CONTENTS_FILE_DESCRIPTOR bit.

Returns
int a bitmask indicating the set of special object types marshaled
by this Parcelable object instance.

Value is either 0 or CONTENTS_FILE_DESCRIPTOR

getBlurBehindRadius

public int getBlurBehindRadius ()

Returns the blur behind radius of the window.

Returns
int

getDesiredHdrHeadroom

public float getDesiredHdrHeadroom ()

Get the desired amount of HDR headroom as set by setDesiredHdrHeadroom(float)

Returns
float The amount of HDR headroom set, or 0 for automatic/default behavior.

getFitInsetsTypes

public int getFitInsetsTypes ()
Returns
int the WindowInsets.Types that this window is avoiding overlapping.

Value is either 0 or a combination of android.view.WindowInsets.Type.STATUS_BARS, android.view.WindowInsets.Type.NAVIGATION_BARS, android.view.WindowInsets.Type.CAPTION_BAR, android.view.WindowInsets.Type.IME, android.view.WindowInsets.Type.WINDOW_DECOR, android.view.WindowInsets.Type.SYSTEM_GESTURES, android.view.WindowInsets.Type.MANDATORY_SYSTEM_GESTURES, android.view.WindowInsets.Type.TAPPABLE_ELEMENT, android.view.WindowInsets.Type.DISPLAY_CUTOUT, and android.view.WindowInsets.Type.SYSTEM_OVERLAYS

getFrameRateBoostOnTouchEnabled

public boolean getFrameRateBoostOnTouchEnabled ()

Get the value whether we should enable touch boost as set
by setFrameRateBoostOnTouchEnabled(boolean)

Returns
boolean A boolean value to indicate whether we should enable touch boost

isFitInsetsIgnoringVisibility

public boolean isFitInsetsIgnoringVisibility ()
Returns
boolean true if this window fits the window insets no matter they are visible or
not.

isFrameRatePowerSavingsBalanced

public boolean isFrameRatePowerSavingsBalanced ()

Get the value whether frameratepowersavingsbalance is enabled for this Window.
This allows device to adjust refresh rate
as needed and can be useful for power saving.
by setFrameRatePowerSavingsBalanced(boolean)

Returns
boolean Whether we should enable frameratepowersavingsbalance.

isHdrConversionEnabled

public boolean isHdrConversionEnabled ()

Returns whether the HDR conversion is enabled for the window

Returns
boolean

mayUseInputMethod

public static boolean mayUseInputMethod (int flags)

Given a particular set of window manager flags, determine whether
such a window may be a target for an input method when it has
focus. In particular, this checks the
FLAG_NOT_FOCUSABLE and FLAG_ALT_FOCUSABLE_IM
flags and returns true if the combination of the two corresponds
to a window that can use the input method.

Parameters
flags int: The current window manager flags.
Returns
boolean Returns true if a window with the given flags would be able to
use the input method, false if not.

setBlurBehindRadius

public void setBlurBehindRadius (int blurBehindRadius)

Blurs the screen behind the window. The effect is similar to that of dimAmount,
but instead of dimmed, the content behind the window will be blurred (or combined with
the dim amount, if such is specified).

The density of the blur is set by the blur radius. The radius defines the size
of the neighbouring area, from which pixels will be averaged to form the final
color for each pixel. The operation approximates a Gaussian blur.
A radius of 0 means no blur. The higher the radius, the denser the blur.

Note the difference with Window.setBackgroundBlurRadius(int),
which blurs only within the bounds of the window. Blur behind blurs the whole screen
behind the window.

Requires FLAG_BLUR_BEHIND to be set.

Cross-window blur might not be supported by some devices due to GPU limitations. It can
also be disabled at runtime, e.g. during battery saving mode, when multimedia tunneling
is used or when minimal post processing is requested. In such situations, no blur will
be computed or drawn, resulting in there being no depth separation between the window
and the content behind it. To avoid this, the app might want to use more
dimAmount on its window. To listen for cross-window blur enabled/disabled
events, use WindowManager.addCrossWindowBlurEnabledListener(Executor, Consumer).

Parameters
blurBehindRadius int: The blur radius to use for blur behind in pixels

Value is 0 or greater

See also:

  • FLAG_BLUR_BEHIND
  • getBlurBehindRadius()
  • WindowManager.addCrossWindowBlurEnabledListener(Executor, Consumer)
  • Window.setBackgroundBlurRadius(int)

setCanPlayMoveAnimation

public void setCanPlayMoveAnimation (boolean enable)

Set whether animations can be played for position changes on this window. If disabled,
the window will move to its new position instantly without animating.

Related XML Attributes:

  • android:windowNoMoveAnimation
Parameters
enable boolean

setDesiredHdrHeadroom

public void setDesiredHdrHeadroom (float desiredHeadroom)

Sets the desired about of HDR headroom to be used when rendering as a ratio of
targetHdrPeakBrightnessInNits / targetSdrWhitePointInNits. Only applies when
setColorMode(int) is ActivityInfo.COLOR_MODE_HDR

Parameters
desiredHeadroom float: Desired amount of HDR headroom. Must be in the range of 1.0 (SDR)
to 10,000.0, or 0.0 to reset to default.

Value is between 0.0f and 10000.0f inclusive

setFitInsetsIgnoringVisibility

public void setFitInsetsIgnoringVisibility (boolean ignore)

Specifies if this window should fit the window insets no matter they are visible or not.

Parameters
ignore boolean: if true, this window will fit the given types even if they are not visible.

setFitInsetsTypes

public void setFitInsetsTypes (int types)

Specifies types of insets that this window should avoid overlapping during layout.

Parameters
types int: which WindowInsets.Types of insets that this window should avoid.
The initial value of this object includes all system bars.

Value is either 0 or a combination of android.view.WindowInsets.Type.STATUS_BARS, android.view.WindowInsets.Type.NAVIGATION_BARS, android.view.WindowInsets.Type.CAPTION_BAR, android.view.WindowInsets.Type.IME, android.view.WindowInsets.Type.WINDOW_DECOR, android.view.WindowInsets.Type.SYSTEM_GESTURES, android.view.WindowInsets.Type.MANDATORY_SYSTEM_GESTURES, android.view.WindowInsets.Type.TAPPABLE_ELEMENT, android.view.WindowInsets.Type.DISPLAY_CUTOUT, and android.view.WindowInsets.Type.SYSTEM_OVERLAYS

setFrameRateBoostOnTouchEnabled

public void setFrameRateBoostOnTouchEnabled (boolean enabled)

Set the value whether we should enable Touch Boost

Parameters
enabled boolean: Whether we should enable Touch Boost

setFrameRatePowerSavingsBalanced

public void setFrameRatePowerSavingsBalanced (boolean enabled)

Set the value whether frameratepowersavingsbalance is enabled for this Window.
This allows device to adjust refresh rate
as needed and can be useful for power saving.

Parameters
enabled boolean: Whether we should enable frameratepowersavingsbalance.

setHdrConversionEnabled

public void setHdrConversionEnabled (boolean enabled)

Enables/disables the HDR conversion for the window.

By default, the HDR conversion is enabled for the window.

Parameters
enabled boolean

setWallpaperTouchEventsEnabled

public void setWallpaperTouchEventsEnabled (boolean enable)

Set whether sending touch events to the system wallpaper (which can be provided by a
third-party application) should be enabled for windows that show wallpaper in
background. By default, this is set to true.
Check FLAG_SHOW_WALLPAPER for more
information on showing system wallpaper behind the window.

Parameters
enable boolean: whether to enable sending touch events to the system wallpaper.

toString

public String toString ()

Returns a string representation of the object.

Returns
String a string representation of the object.

writeToParcel

public void writeToParcel (Parcel out, 
                int parcelableFlags)

Flatten this object in to a Parcel.

Parameters
out Parcel: The Parcel in which the object should be written.
This value cannot be null.
parcelableFlags int: Additional flags about how the object should be written.
May be 0 or Parcelable.PARCELABLE_WRITE_RETURN_VALUE.

Value is either 0 or a combination of Parcelable.PARCELABLE_WRITE_RETURN_VALUE, and android.os.Parcelable.PARCELABLE_ELIDE_DUPLICATES

If enableEdgeToEdge sucks for your Android activity’s Compose UI, try this instead!

Go Edge-to-Edge on Android in a More Customizable Way

Google currently recommends calling enableEdgeToEdge() in order to make your Compose UI go edge-to-edge.
However, the result it yields may be slightly different from how you really want your app’s activity to look.
For example, an unwanted semi-transparent scrim may appear behind the navigation bar.
Don’t worry, it’s actually possible to tweak most of this stuff!

Here I show the three steps I take to go edge-to-edge. You can try it yourself and see if you like it too!
If you have any questions, suggestions for improvement or your own preferred solutions,
feel free to leave a comment down below, I’m open and curious to read them!

1. Set Decor Fits System Windows to false

This is done to tell Android that our activity wants to draw content where system bars usually are.

Instead of using enableEdgeToEdge(), I still use the good old WindowCompat.setDecorFitsSystemWindows(window, false)
in my activity’s onCreate method. Why? Because enableEdgeToEdge() draws a visible scrim behind
the navigation bar, even if you tell it to make it transparent, and I don’t want that!

// MainActivity.kt

// ...
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // ===== Hello-hello, the line below! =====
    WindowCompat.setDecorFitsSystemWindows(window, false)
    // ===== Bye-bye, the poor next line! =====
    // enableEdgeToEdge()
    // ...

Some folks suggest using android:fitsSystemWindows="false" in the activity’s manifest attributes,
but it never made a dent for what I could see, so I ditched it. Instead, I add another manifest attribute:
android:windowSoftInputMode="adjustResize", which is a different thing entirely, but I’ll thank
myself later when I realize that otherwise my software keyboard covers up half the activity,

2. Tweak system bars’ appearance in your XML themes

In the style resources, also known as themes, it’s possible to set desired system bar colors and disable the system scrims.
Wait, what? More scrims? Yes, there are also system scrims for the system bars, and I don’t want them either!

So first I go to the default theme and set the system bar colors to transparent.

<!-- values/themes.xml -->

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="Theme.ArchitectureTestApp" parent="android:Theme.Material.Light.NoActionBar">
        <!-- ===== These two lines below ===== -->
        <item name="android:statusBarColor">@android:color/transparent</item>
        <item name="android:navigationBarColor">@android:color/transparent</item>
    </style>
</resources>

Then I do the same thing for the dark night theme. And yes, a separate values-night theme XML is a must,
because otherwise the app’s default splash screen will be light, which will burn the users’ eyes!

<!-- values-night/themes.xml -->

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- For the users' eyes' sake please make sure it's Material, not Material.Light -->
    <style name="Theme.Main" parent="android:Theme.Material.NoActionBar">
        <!-- ===== These two lines below again ===== -->
        <item name="android:statusBarColor">@android:color/transparent</item>
        <item name="android:navigationBarColor">@android:color/transparent</item>
    </style>
</resources>

Then I disable the system scrims. Since the style items that offer such options are only available since
Android API level 29 (Android 10 «Quince Tart»), I’m doing this in values-v29.

<!-- values-v29/themes.xml -->

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="Theme.Main" parent="android:Theme.Material.Light.NoActionBar">
        <!-- ===== Yep, these four lines below ===== -->
        <item name="android:enforceStatusBarContrast">false</item>
        <item name="android:enforceNavigationBarContrast">false</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
        <item name="android:navigationBarColor">@android:color/transparent</item>
    </style>
</resources>

Same goes for the dark values-night-v29 theme.

<!-- values-night-v29/themes.xml -->

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- Again, Material, not Material.Light, remember? -->
    <style name="Theme.Main" parent="android:Theme.Material.NoActionBar">
        <!-- ===== Mm-hmm, these four lines below again, you get it ===== -->
        <item name="android:enforceStatusBarContrast">false</item>
        <item name="android:enforceNavigationBarContrast">false</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
        <item name="android:navigationBarColor">@android:color/transparent</item>
    </style>
</resources>

Alright then! At this point I might want to play around with some more specific theme tweaks depending on the design,
but the main job is done: the bars are now transparent and my activity can draw whatever I want behind them.

Except for one more little thing I also gotta do…

3. Set the system bars’ content brightness

I want to make sure that the foreground content of the system bars is properly visible on top of my activity:
when the dark theme is enabled in Compose UI, I want the system bars’ foreground content to appear light,
and when the light theme is enabled, I want the foreground content to appear dark.

Since I made the system bars transparent, it is now my Compose theme’s responsibility to tell the
insets controller if the background is light or dark, so that the system knows whether the
bars’ foreground content should be dark or light.

And guess what? This is exactly what the following code does, and I use it right in my app’s theme composable.

// Theme.kt

// ...
@Composable
fun MainTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    dynamicColor: Boolean = true,
    content: @Composable () -> Unit, // Obsessed with trailing commas!
) {
    // ...

    // ===== These nine lines below =====
    val view = LocalView.current
    if (!view.isInEditMode) {
        SideEffect {
            val window = (view.context as Activity).window
            val insets = WindowCompat.getInsetsController(window, view)
            insets.isAppearanceLightStatusBars = !darkTheme
            insets.isAppearanceLightNavigationBars = !darkTheme
        }
    }
    // ===== These nine lines above =====

    MaterialTheme(
        // ...
        content = content, // Still obsessed, thanks for asking!
    )
}

A major­i­ty of Android devices have a soft­ware nav­i­ga­tion bar which (for every oth­er app I can think of) is a sol­id black (or white) bar that takes up 48dp of your ver­ti­cal screen space. On the Google Pix­el this equates to some­where between 7 – 10% of the total ver­ti­cal screen space (depend­ing on your acces­si­bil­i­ty set­tings for screen size). Con­sid­er­ing that most mobile apps are opti­mized for show­ing you a list of things in a win­dow that scrolls ver­ti­cal­ly, we might want to reclaim some of this space for the con­tent of our apps. This will make your app feel more immer­sive by using more of the screen to dis­play your con­tent. You could cer­tain­ly hide the nav­i­ga­tion UI alto­geth­er, but this makes it more dif­fi­cult for the user to nav­i­gate between screens in your app because they will have to swipe up from the bot­tom of the screen to reveal the hid­den nav­i­ga­tion bar. I stum­bled on a bet­ter answer by acci­dent when I noticed that the news feed sec­tion of the Pix­el launch­er has a semi-trans­par­ent bot­tom nav­i­ga­tion bar:

Google Feed

As it turns out, this translu­cent navbar option has been around since KitKat (API Lev­el 19)! All you have to do is set android:windowTranslucentNavigation to true and it just works, right?

The Part Where it Gets Com­pli­cat­ed #

Nope, sor­ry, I lied. Even though we’ve request­ed that the app be shown with a translu­cent nav­i­ga­tion bar, the app’s win­dow still is sized to the area between the nav­i­ga­tion bar and the sta­tus­bar. For­tu­nate­ly, the KitKat release notes help­ful­ly explain that in order to get your app to dis­play con­tent under the nav­i­ga­tion bar, you must also set android:fitsSystemWindows to false. This allows the Activity’s win­dow to be drawn at the full size of the device’s screen.

By this point, you’ve prob­a­bly won­dered How do I tap on items that are dis­played under­neath the nav­i­ga­tion bar?” The answer is You can’t” because the nav­i­ga­tion bar does not pass touch events through to your appli­ca­tion. There­fore, we have to add padding to the bot­tom of the app’s con­tent so that it can be scrolled into an acces­si­ble posi­tion above the nav­i­ga­tion bar. The amount of padding required is sim­ply the height of the navbar which be deter­mined by retriev­ing the val­ue of android.R.dimen.navigation_bar_height from the sys­tem resources:

val Resources.navBarHeight: Int @Px get() {
  val id = getIdentifier("navigation_bar_height", "dimen", "android")
  return when {
    id > 0 -> getDimensionPixelSize(id)
    else -> 0
  }
}

Then apply that many pix­els of padding to the bot­tom of your layout’s scrolling ele­ment (in this exam­ple, a RecyclerView):

recyclerView.setPaddingRelative(
  recyclerView.paddingStart,
  recyclerView.paddingTop,
  recyclerView.paddingEnd,
  recyclerView.paddingBottom + resources.navBarHeight
)

You will also need to set android:clipToPadding to false on your RecyclerView or ScrollView oth­er­wise Android will not draw any child views inside the padding area.

What About Hard­ware Nav­i­ga­tion But­tons? #

Phones such as the Sam­sung Galaxy S7 use phys­i­cal but­tons for the Back/​Home/​Switcher actions and do not show the soft­ware nav­i­ga­tion bar on the screen. Some of these even let you choose between the hard­ware but­tons and the onscreen but­tons. For­tu­nate­ly, we can read android.R.bool.config_showNavigationBar to deter­mine if the soft­ware navbar is being shown:

val Resources.showsSoftwareNavBar: Boolean get() {
  val id = getIdentifier("config_showNavigationBar", "bool", "android")
  return id > 0 && getBoolean(id)
}

// Inset bottom of content if drawing under the translucent navbar, but
// only if the navbar is a software bar
if (resources.showsSoftwareNavBar) {
  recyclerView.setPaddingRelative(/* ... */)
}

Every­thing Goes Side­ways #

Rota­tion con­fig­u­ra­tion changes have always been tricky for Android apps to han­dle and this is no dif­fer­ent. When you rotate a phone into the 90° or 270° ori­en­ta­tion, the nav­i­ga­tion bar remains on the side of the phone that is the bot­tom” in the 0° ori­en­ta­tion. In these ori­en­ta­tions, dis­play­ing con­tent under the navbar los­es its use­ful­ness, so we’ll dis­able it. The eas­i­est way to do this is by over­rid­ing these attrib­ut­es of the activity’s theme based on orientation:

<!-- values/styles.xml -->
<bool name="fullscreen_style_fit_system_windows">false</bool>
<bool name="fullscreen_style_use_translucent_nav">true</bool>
<style name="AppTheme.Fullscreen">
    <item name="android:fitsSystemWindows">
        @bool/fullscreen_style_fit_system_windows
    </item>
    <item name="android:windowTranslucentNavigation">
        @bool/fullscreen_style_use_translucent_nav
    </item>
</style>

<!-- values-land/styles.xml -->
<bool name="fullscreen_style_fit_system_windows">true</bool>
<bool name="fullscreen_style_use_translucent_nav">false</bool>

We will also have to add the padding to the scrolling con­tent of the view conditionally:

inline val Resources.isNavBarAtBottom: Boolean get() {
  // Navbar is always on the bottom of the screen in portrait mode, but rotates
  // with device in landscape orientations
  return this.configuration.orientation == ORIENTATION_PORTRAIT
}

// Inset bottom of content if drawing under the translucent navbar, but
// only if the navbar is a software bar and is on the bottom of the screen.
if (resources.showsSoftwareNavBar && resources.isNavBarAtBottom) {
  recyclerView.setPaddingRelative(/* ... */)
}

But wait! What about tablets? Tablets do rotate the navbar to the bot­tom of the screen in all ori­en­ta­tions. There is no isTablet prop­er­ty pro­vid­ed by Android since the def­i­n­i­tion of tablet” is rather ambigu­ous in the pres­ence of large phablet” phones, so we have to cre­ate our own. Android treats devices with a screen whose small­est dimen­sion is at least 600dp dif­fer­ent­ly, most impor­tant­ly for our use case, let­ting the nav­i­ga­tion bar rotate. We can again use resource splits to cre­ate dif­fer­ent val­ues for isTablet depend­ing on the device’s screen that we can check in our code:

<!-- values/bools.xml -->
<bool name="is_tablet">false</bool>

<!-- values-sw600dp/bools.xml -->
<bool name="is_tablet">true</bool>
inline val Resources.isTablet: Boolean get() = getBoolean(R.bool.is_tablet)

inline val Resources.isNavBarAtBottom: Boolean get() {
  // Navbar is always on the bottom of the screen in portrait mode, but may
  // rotate with device if its category is sw600dp or above.
  return this.isTablet || this.configuration.orientation == ORIENTATION_PORTRAIT
}

Catch 24 #

Android 7.0 Nougat (API 24) intro­duced yet anoth­er ele­ment for us to wor­ry about: Mut­li-Win­dow mode. In Mul­ti-Win­dow mode, two activ­i­ties may be shown side-by-side or stacked ver­ti­cal­ly depend­ing on device ori­en­ta­tion and nei­ther app gets to draw under the nav­i­ga­tion bar. Since we can­not per­form any of our fan­cy nav­i­ga­tion bar styling in these cas­es, we will dis­able our mod­i­fi­ca­tions to the activ­i­ty theme and padding applied to the con­tent in Mul­ti-Win­dow mode:

inline val Activity.isInMultiWindow: Boolean get() {
  return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    isInMultiWindowMode
  } else {
    false
  }
}

// Apps can't draw under the navbar in multiwindow mode.
val fitSystemWindows = if (activity?.isInMultiWindow == true) {
  true
} else {
  resources.getBoolean(R.bool.fullscreen_style_fit_system_windows)
}
// Override the activity's theme when in multiwindow mode.
coordinatorLayout.fitsSystemWindows = fitSystemWindows

if (!fitSystemWindows) {
  // Inset bottom of content if drawing under the translucent navbar, but
  // only if the navbar is a software bar and is on the bottom of the screen.
  if (resources.showsSoftwareNavBar && resources.isNavBarAtBottom) {
    recyclerView.setPaddingRelative(/* ... */)
  }
}

One More Thing #

With fitsSystemWindows="false", the Activ­i­ty is also drawn under­neath the sta­tus­bar, which we have com­plete­ly ignored so far. For­tu­nate­ly, its behav­ior is much more pre­dictable than the nav­i­ga­tion bar since it is always shown on all phones (except when explic­it­ly hid­den by the activ­i­ty theme, which we did not do), and it is always shown at the top of the screen. Thus, whether we add padding to our AppBarLayout or not will fol­low the fitSystemWindows set­ting with no exceptions:

val Resources.statusBarHeight: Int @Px get() {
  val id = getIdentifier("status_bar_height", "dimen", "android")
  return when {
    id > 0 -> getDimensionPixelSize(id)
    else -> 0
  }
}

if (!fitSystemWindows) {
  // ...
  // Inset the toolbar when it is drawn under the status bar.
  barLayout.updatePaddingRelative(
    barLayout.paddingStart,
    barLayout.paddingTop + resources.statusBarHeight,
    barLayout.paddingEnd,
    barLayout.paddingBottom
  )
}

A Piece of Everyone’s Least Favorite Can­dy #

Right at the begin­ning, I said that KitKat was the Android ver­sion that enabled use of translu­cent nav­i­ga­tion bars, but like so many things in KitKat, you can’t get it to work prop­er­ly. The config_showNavigationBar val­ue that we check to see if we need to inset the scrolling con­tent always returns false when fitsSystemWindows is false. The navigation_bar_height dimen­sion also always returns 0 in this case, mak­ing it impos­si­ble to mea­sure how much padding we should add to the con­tent. To imple­ment our solu­tion on KitKat we have to assume the device always has a soft­ware nav­i­ga­tion bar (which is less and less like­ly the old­er the device is), esti­mate the padding required (almost always 48dp, 56dp for tablets meet­ing the sw900dp qual­i­fi­er), and just deal with excess space at the bot­tom for devices that don’t. That’s too many con­di­tions to leave to chance (espe­cial­ly for KitKat), so I’ve opt­ed to dis­able the translu­cent navbar using anoth­er resource split:

<!-- values/styles.xml -->
<bool name="fullscreen_style_fit_system_windows">true</bool>
<bool name="fullscreen_style_use_translucent_nav">true</bool>
<style name="AppTheme.Fullscreen">
  <!-- KitKat can show a translucent navbar, but config_showNavigationBar
    is always false so you can't really tell if the device has hardware nav
    keys or not. -->
  <item name="android:fitsSystemWindows">
    @bool/fullscreen_style_fit_system_windows
  </item>
</style>

<!-- values-v21/styles.xml -->
<bool name="fullscreen_style_fit_system_windows">false</bool>
<style name="AppTheme.Fullscreen">
  <item name="android:fitsSystemWindows">
    @bool/fullscreen_style_fit_system_windows
  </item>
  <item name="android:windowTranslucentNavigation">
    @bool/fullscreen_style_use_translucent_nav
  </item>
</style>

Con­clu­sion #

There’s a lot of stuff to keep in mind here, so I’ve made a sam­ple app demon­strat­ing all these con­cepts avail­able on GitHub. If you’d like to play around with the app, it is also avail­able on the Google Play Store. It’s a very sim­ple exam­ple that shows the col­ors of the Mate­r­i­al palette in a grid:

Translucent Navbar

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как сменить локальную учетную запись windows 10 на майкрософт
  • Управление оборотами кулера windows
  • Windows css styles for sites skinapp
  • Driver hp laserjet 1200 series windows 7
  • Openvpn установка клиента windows