Скрыть панель навигации
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
В этом уроке описывается, как скрыть панель навигации, которая появилась в Android 4.0 (уровень API 14).
Несмотря на то, что этот урок посвящен сокрытию панели навигации, вам следует спроектировать свое приложение так, чтобы в то же время скрывать строку состояния, как описано в разделе «Скрытие строки состояния» . Скрытие строк навигации и состояния (при сохранении их легкого доступа) позволяет содержимому использовать все пространство дисплея, тем самым обеспечивая более захватывающий пользовательский опыт.

Рисунок 1. Панель навигации.
Скрыть панель навигации
Вы можете скрыть панель навигации, используя флаг SYSTEM_UI_FLAG_HIDE_NAVIGATION
. Этот фрагмент скрывает как панель навигации, так и строку состояния:
Котлин
window.decorView.apply {
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
}
Ява
View decorView = getWindow().getDecorView();
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
Обратите внимание на следующее:
- При таком подходе прикосновение к любому месту экрана приводит к тому, что панель навигации (и строка состояния) появляется снова и остается видимой. В результате взаимодействия с пользователем флаги сбрасываются.
- После очистки флагов вашему приложению необходимо сбросить их, если вы хотите снова скрыть панели. См. раздел «Реакция на изменения видимости пользовательского интерфейса» , где обсуждается, как прослушивать изменения видимости пользовательского интерфейса, чтобы ваше приложение могло реагировать соответствующим образом.
- То, где вы устанавливаете флаги пользовательского интерфейса, имеет значение. Если вы скроете системные панели в методе
onCreate()
своей активности и пользователь нажмет «Домой», системные панели появятся снова. Когда пользователь повторно открывает действие, onCreate()
не будет вызываться, поэтому системные панели останутся видимыми. Если вы хотите, чтобы изменения системного пользовательского интерфейса сохранялись, когда пользователь входит в вашу деятельность и выходит из нее, установите флаги пользовательского интерфейса в onResume()
или onWindowFocusChanged()
. - Метод
setSystemUiVisibility()
имеет эффект только в том случае, если представление, из которого вы его вызываете, видимо. - Выход из представления приводит к очистке флагов, установленных с помощью
setSystemUiVisibility()
.
Сделайте контент видимым за панелью навигации
В Android 4.1 и более поздних версиях вы можете настроить отображение содержимого вашего приложения за панелью навигации, чтобы размер содержимого не изменялся при скрытии и отображении панели навигации. Для этого используйте SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
. Вам также может потребоваться использовать SYSTEM_UI_FLAG_LAYOUT_STABLE
чтобы помочь вашему приложению поддерживать стабильный макет.
Когда вы используете этот подход, вы несете ответственность за то, чтобы критические части пользовательского интерфейса вашего приложения не закрывались системными панелями. Более подробное обсуждение этой темы см. в уроке «Скрытие строки состояния» .
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-07-29 UTC.
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 2025-07-29 UTC."],[],[],null,["# Hide the navigation bar\n\nThis lesson describes how to hide the navigation bar, which was introduced in\nAndroid 4.0 (API level 14).\n\nEven though this lesson focuses on hiding the\nnavigation bar, you should design your app to hide the status bar\nat the same time, as described in [Hiding the Status Bar](/training/system-ui/status).\nHiding the navigation and status bars (while still keeping them readily accessible)\nlets the content use the entire display space, thereby providing a more immersive\nuser experience.\n\n**Figure 1.** Navigation bar.\n\nHide the Navigation Bar\n-----------------------\n\nYou can hide the navigation bar using the\n[SYSTEM_UI_FLAG_HIDE_NAVIGATION](/reference/android/view/View#SYSTEM_UI_FLAG_HIDE_NAVIGATION) flag. This snippet hides both\nthe navigation bar and the status bar: \n\n### Kotlin\n\n```kotlin\nwindow.decorView.apply {\n // Hide both the navigation bar and the status bar.\n // SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as\n // a general rule, you should design your app to hide the status bar whenever you\n // hide the navigation bar.\n systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN\n}\n```\n\n### Java\n\n```java\nView decorView = getWindow().getDecorView();\n// Hide both the navigation bar and the status bar.\n// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as\n// a general rule, you should design your app to hide the status bar whenever you\n// hide the navigation bar.\nint uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_FULLSCREEN;\ndecorView.setSystemUiVisibility(uiOptions);\n```\n\nNote the following:\n\n- With this approach, touching anywhere on the screen causes the navigation bar (and status bar) to reappear and remain visible. The user interaction causes the flags to be be cleared.\n- Once the flags have been cleared, your app needs to reset them if you want to hide the bars again. See [Responding to UI Visibility Changes](/training/system-ui/visibility) for a discussion of how to listen for UI visibility changes so that your app can respond accordingly.\n- Where you set the UI flags makes a difference. If you hide the system bars in your activity's [onCreate()](/reference/android/app/Activity#onCreate(android.os.Bundle)) method and the user presses Home, the system bars will reappear. When the user reopens the activity, [onCreate()](/reference/android/app/Activity#onCreate(android.os.Bundle)) won't get called, so the system bars will remain visible. If you want system UI changes to persist as the user navigates in and out of your activity, set UI flags in [onResume()](/reference/android/app/Activity#onResume()) or [onWindowFocusChanged()](/reference/android/view/Window.Callback#onWindowFocusChanged(boolean)).\n- The method [setSystemUiVisibility()](/reference/android/view/View#setSystemUiVisibility(int)) only has an effect if the view you call it from is visible.\n- Navigating away from the view causes flags set with [setSystemUiVisibility()](/reference/android/view/View#setSystemUiVisibility(int)) to be cleared.\n\nMake Content Appear Behind the Navigation Bar\n---------------------------------------------\n\nOn Android 4.1 and higher, you can set your application's content to appear behind\nthe navigation bar, so that the content doesn't resize as the navigation bar hides and\nshows. To do this, use\n[SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION](/reference/android/view/View#SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION).\nYou may also need to use\n[SYSTEM_UI_FLAG_LAYOUT_STABLE](/reference/android/view/View#SYSTEM_UI_FLAG_LAYOUT_STABLE) to help your app maintain a\nstable layout.\n\nWhen you use this approach, it becomes your responsibility to ensure that critical parts\nof your app's UI don't end up getting covered by system bars. For more\ndiscussion of this topic, see the [Hiding the Status Bar](/training/system-ui/status#behind) lesson."]]