- Transparent Android system navigation bar with Flutter and FlexColorScheme
- Sysnavbar with FlexColorScheme
- About this Example
- Android setup
- Support both transparent and color branded sysnavbar
- Translucent SystemBars the right way — across API levels and themes
- Capability
- Solution
- Base values:
- AppBarLayout:
- v21 — v22:
- 1. Use different backgrounds for dark and light themes.
- 2. [chosen]Use same background for dark and light themes.
- [Android Q] Transparent navigation bar with extended scaffold #34678
- Comments
- Zazo032 commented Jun 18, 2019
- bernaferrari commented Jun 20, 2019 •
- shihaohong commented Aug 1, 2019
- shihaohong commented Aug 2, 2019 •
- bernaferrari commented Aug 2, 2019
- gaurav414u commented Aug 27, 2019
- shihaohong commented Aug 27, 2019
- gaurav414u commented Aug 27, 2019
- shihaohong commented Aug 31, 2019 •
- gaurav414u commented Aug 31, 2019
- TheJulianJES commented Aug 31, 2019
- shihaohong commented Aug 31, 2019 •
- JavierSegoviaCordoba commented Sep 25, 2019
- rydmike commented Sep 25, 2019
- Navigation Drawer в стиле Material Design за 5 минут
- Создание проекта
- Android Support Library
- Подключение библиотеки MaterialDrawer
- Подготовка разметки для Navigation Drawer
- Инициализация Navigation Drawer
- Улучшения Navigation Drawer
Transparent Android system navigation bar with Flutter and FlexColorScheme
Sysnavbar with FlexColorScheme
Transparent Android system navigation bar with Flutter and FlexColorScheme.
About this Example
This an extra Android companion example to the Flutter
package FlexColorScheme.
It is a slight modification of example nr 5 bundled with the package and shows
how FlexColorScheme can be used to make a transparent system navigation bar in
Flutter Android applications.
Android setup
To make transparent system navigation bar in Flutter you must also make this change to them MainActivity.kt
file in your Flutter Android embedder:
in ../android/app/src/main the default MainActivity.kt for your project:
Additionally, you must use Android SDK 30 to build the Flutter Android project, so you also need to update
your build.gradle file in ../android/app from:
You can find additional info and discussion about transparent system navigation in Flutter Android apps in
Flutter issue 69999, it was that discussion that lead me
to adding this experimental support for it in FlexColorScheme.
Support both transparent and color branded sysnavbar
When you want to use color branded system navigation bar it is best to never put any transparency on it if it is not
supported. Adding transparency to the system navigation bar color when it is not supported, will just make
the color on it transparent and show the default scrim color used on the system navigation bar. This will not look
very nice.
If you design your app to use transparent system navigation bar when it is supported, and then want to use and have a
nice looking color branded background colored system navigation bar, when transparency is not supported, then we must
check which Android SDK level the application is running on and adjust the behaviour accordingly. We can use the
package device_info to get the Android SDK level and keep the opacity as 1 when SDK level is below 30.
This example presents one suggestion on how this can be implemented, and the different approach to the design for
the use cases.
In the sub-page in this example, it also shows how you can use a fully transparent system navigation bar when possible,
and for the case when this is not possible, a color branded opaque one. Then combine this with a same background primary
color branded Material BottomNavigationBar using a slight transparency. For the case that support
transparency on the system navigation bar, when it is placed on top of this BottomNavigationBar with its slight
transparency, it makes BottomNavigationBar and system navigation bar look like one shared translucent bottom area,
with content scrolling behind it.
For the case when the system navigation bar transparency is not supported, it still has
the same color as the BottomNavigationBar , but without the transparency, so it does not clash so badly
with it. The BottomNavigationBar still keeps it slight transparency, and we can at least see content scrolling behind
it.
Instead of just transparency on the bottom navigation bar, you can add a container to it with blur filter in it,
you can then recreate the iOS frosted glass blur effect and have that on the system navigation bar too.
This is not shown in this demo, but is e.g. used by one of the configuration options offered for Material
BottomNavigationBar in Flexfold.
The end result is an app looking like the left one, when transparency is supported and like the right one,
when it is not. I kind of like it.
Источник
Translucent SystemBars the right way — across API levels and themes
To draw edge to edge with translucent status and navigation bars on v21+ with dark and light themes.
This article assumes you have already gone through Gesture Navigation- Going Edge to Edge (I)
Since we want the content to be drawn behind the system bars, it means that
- We need translucency
- We need either dark or light scrims for navigation bar and statusBar as per the current theme.
Capability
- Fully configurable statusBarColor
But we are limited to using darker colors as the statusBar icons remain white colored. - windowTranslucentStatus true will override statusBarColor and apply a fixed dark scrim that can’t be changed.
- Fully configurable navigationBarColor
But we are limited to using darker colors as the navigation buttons remain white colored. - windowTranslucentNavigation true will override navigation BarColor and apply a fixed dark scrim that can’t be changed.
- Status bar icons & navigation bar buttons always remain light.
- windowLightStatusBar
Enables the statusBar icons to be dark
- windowLightNavigationBar
Enables the navigation bar buttons to be dark.
Solution
Note: We will be using a transparent statusBarColor. Because we will instead use AppBar to color the statusBar. Since the AppBar covers the statusBar’s area, it should be enough to set the relevant background to AppBar directly.
In your implementation, this can be any view that is on the top. If there is no view on the top of the screen , you can instead use statsuBarColor attribute. It will give the same results.
Base values:
AppBarLayout:
v21 — v22:
- We ditch windowTranslucentStatus and windowTranslucentNavigation, as the system will apply a dark scrim if we use them.
- statusBar and navigationBar icons remain white colored.
- Means, we can only use dark backgrounds/scrims.
We got 2 options here:
1. Use different backgrounds for dark and light themes.
In case of dark theme the colorSurface will be dark/black. We can use a similar color for systemBars as well.
In case of light theme, the colorSurface will be light/white. We can’t use a similar color for systembars as the icons are white.
Basically, we can’t handle light themed system bars very well on v21–22. So we are left with using dark backgrounds only .
2. [chosen]Use same background for dark and light themes.
We can work our way by using dark backgrounds for dark and light themes.
Источник
[Android Q] Transparent navigation bar with extended scaffold #34678
Comments
Zazo032 commented Jun 18, 2019
In Android Q, when using the new full gesture navigation, if an app has a transparent navigation bar, the gestural navigation area is floating over the app, and no black or white navigation bar is shown.
Seems to be an easy addition but right now I didn’t manage to make it work. I tried to set transparent navigation bar but it is not working properly as the navigation bar is still black or white (in Android Q). If the navigation bar is enabled, the Scaffold may also need to be extended a bit more so it is shown under de gestures area.
The text was updated successfully, but these errors were encountered:
bernaferrari commented Jun 20, 2019 •
While this has been a hot topic now, Google is recommending to use transparent navigation bar everywhere, not only in Q. Since users in Q will be able to choose between the new and the old navigation bar, we should just use the entire display for most apps and add a bottom padding to lists.
shihaohong commented Aug 1, 2019
This is related to #32748, just adding this in to tie all Android Q issues together
shihaohong commented Aug 2, 2019 •
Actually, I believe removing the bottom navigation bar is already possible with SystemChrome. setEnabledSystemUIOverlays. What you have to do is import package:flutter/services.dart , then call:
The main piece that’s missing is how to determine the system gesture window insets, which I’m currently working on
bernaferrari commented Aug 2, 2019
There is a problem. You don’t want this:
On Android it’s recommended that you keep FAB and etc at relative 16 (i.e. in the safe area) because.. well, as you saw there, you don’t know the height of the bar. On iOS, Google has been using absolute 16 because the bar height is always the same.
gaurav414u commented Aug 27, 2019
Any updates on this?
When do you guys plan to get it fixed and merged?
@shihaohong
shihaohong commented Aug 27, 2019
What is the particular ask? It’s already currently possible to set a transparent navigation bar using the SystemChrome API
gaurav414u commented Aug 27, 2019
So, I am able to make the navigation bar transparent but I cannot draw a layout behind the navigation bar.
shihaohong commented Aug 31, 2019 •
I will close this for now, since it seems like it is possible to create a transparent navigation bar that allows the Scaffold to extend behind the Android Q nav bar using SystemChrome.setEnabledSystemUIOverlays.
However, if there seems to be more precise asks, please feel free to file new issues so that we can track individual needs. Every contribution to this issue seems to be asking for slightly different things (ie transparent Android Q nav bar, making the nav bar transparent while still exposing system windows insets regardless of Android SDK version, etc).
gaurav414u commented Aug 31, 2019
Hey @shihaohong how about post-Lollipop and pre-Q devices?
TheJulianJES commented Aug 31, 2019
I’m thinking that just setting the navigation bar to transparent using SystemChrome.setEnabledSystemUIOverlays doesn’t create the padding (for lists and more).
This already happens on iOS (with iPhone X or later), as we get a padding for the home bar there.
shihaohong commented Aug 31, 2019 •
As per my original comment, please file a new issue with reproducible samples for unique, specific asks. It’s hard to keep track of what needs to be done to account for full screen navigation when there are different permutations of needs by different developers.
JavierSegoviaCordoba commented Sep 25, 2019
@shihaohong SystemChrome.setEnabledSystemUIOverlay this is a hack, I don’t want a semi-fullscreen app.
rydmike commented Sep 25, 2019
Reading all the comments here and having struggled wit this too, I think it is fairly obvious what is asked for.
A way to to make a fully transparent Android system navigation bar where only the Android navigation buttons are opaque (or semi transparent) that also plays nice with other bottom widgets used in Flutter. Meaning e.g a FAB or a bottom navigation bar should remain above the transparent navigation button area if used, but the scaffold content should paint (scroll) behind them all. It might be a good idea to have it as an option that the bottom navbars and FAB can optionally start from the «true» bottom too, then you will of course get the situation that was shown in the screenshot above, which in some special design cases might be desired or at least a needed starting point for the layout.
More discussion on the topic
Combined with the Scaffold’s extendBody property and the new extendBodyBehindAppBar #39156 property, that now also extends the body behind the top system statusbar icons, we can now in Flutter easily make «fullscreen» designs that have become fairly popular, for certain apps at least.
The AppBar overlay on the top system statusbar can already be made fully or semi transparent, and now the scaffold body content can then scroll nicely behind the transparent/semitransparent (like in #39156) or even use a partial appbar, like e.g. the floating search appbar in the Android GMail app.
For a fully nice full screen look it should be possible to extend the same look and design at the bottom too behind the navigation button and nav area, as many android apps with newer designs do.
Currently it is as far as I can tell impossible to do this in Flutter on Android. It seem impossible to make the Android navigation bar transparent and have correctly colored buttons in flutter and keeping the Flutter widgets that deal with the bottom area correctly.
I have tried a solution that was based on how to modify the AndroidManifest, this got me close to the desired outcome. If I recall correctly I got a semitransparent navigation bar area, but not a fully transparent one, not on the Pixel 3XL emulator at least. Additionally Flutter’s widgets got a bit confused with this approach concerning e.g. its own bottom navigation bar buttons, that then got drawn under the (semi)transparent system navigation bar and its opaque buttons, making it impossible to tap and use the Flutter bottom navigation bar buttons. I’m sure the Flutter bottom navbar could be modified or just build your own that you can move up a bit, but it becomes a bit complex to figure out on which devices it is needs to move where. It would be helpful and useful if there was a clear and easy approach for solving this built into the framework.
There is now a nice solution for the top area, but as far as I can tell the navbar area still requires some improvements to make it fully baked.
Finally, if there is some working solution I would be happy and eager to learn about it, because so far I have not found one.
Источник
Navigation Drawer в стиле Material Design за 5 минут
В данной статье я расскажу, как быстро добавить в ваше приложение для Android боковое меню (aka Navigation Drawer) в стиле Material Design. Для этого мы воспользуемся библиотекой, любезно предоставленной Mike Penz.
У вас получится Navigation Drawer, который:
- Соответствует последним рекомендациям по дизайну (Google Material Design Guidelines);
- Поддерживает использование нескольких Drawer (можно выдвигать второй справа);
- Поддерживает использование бейджей;
- Имеет простой и понятный интерфейс (API);
- Может выползать как под, так и поверх Status Bar;
- Позволяет менять иконки, цвета, бейджи во время выполнения;
- Использует AppCompat support library;
- Работает, начиная с API 14.
Помимо этого, новички обучатся интеграции сторонних библиотек в свой проект, что крайне полезно, учитывая их грандиозное разнообразие на Github.
Создание проекта
В примере будет использоваться интегрированная среда разработки Android Studio от компании Google, основанная на IntelliJ IDEA, которую сама корпорация активно продвигает. Все действия можно воспроизвести используя и другие среды, например, Eclipse. Однако статья ориентирована на новичков, а они будут в большинстве своем использовать именно Android Studio, так как именно его Google теперь и предлагает при скачивании Android SDK с developer.android.com (ранее можно было скачать Eclipse).
Итак, выбираем в меню «File» -> «New Project. »:
Заполняем имя приложения, пакета, выбираем SDK.
Создавать проект мы будем с поддержкой минимального API Level равного 14, что соответствует Android 4.0 Ice Cream Sandwich, поскольку всё, что ниже, составляет менее 8% аудитории и привносит несоизмеримо большее количество головной боли:
В последних двух окнах оставляем все по умолчанию, жмем «Finish».
Android Support Library
Для того, чтобы красивый Navigation Drawer работал на версиях Android ниже 5.0 и выглядел в стиле Material Design, необходимо включить в проект библиотеку поддержки от Google, которая носит название v7 appcompat library. В текущей версии Android Studio (1.0.2) библиотека подключается по умолчанию при создании проекта. Проверьте это в файле проекта \app\build.gradle, в разделе dependencies должна быть строка (цифры могут быть не обязательно «21.0.3»):
а класс MainActivity должен наследоваться от ActionBarActivity
Также проверьте в \res\values\styles.xml, чтобы тема приложения наследовалась от Theme.AppCompat или ее вариаций без ActionBar (мы заменим ActionBar на ToolBar), например:
Подключение библиотеки MaterialDrawer
Добавьте в раздел dependencies файла \app\build.gradle строки
и нажмите появившуюся в верхней части окна кнопку «Sync Now» для синхронизации вашего проекта.
Подготовка разметки для Navigation Drawer
В главный layout приложения нужно добавить ToolBar. Приведите activity_main.xml к такому виду:
Создайте в папке layout файл drawer_header.xml со следующим содержанием
этот файл — разметка для верхней части Drawer’a, в которой находится картинка. Теперь положите в папку \res\drawable\ любую картинку с именем header.jpg, которая будет отображаться в верхней части Drawer’a, например эту:
Файл \res\strings.xml, содержащий строковые ресурсы, приведите к следующему виду
Инициализация Navigation Drawer
В методе onCreate вашей MainActivity мы инициализируем ToolBar, добавьте после setContentView следующий код:
Затем инициализируем и сам Navigation Drawer, добавьте ниже:
В случае появления ошибок, убедитесь, что ваша секция импортов в MainActivity выглядит так:
Теперь можно запустить приложение и оценить результат:
Улучшения Navigation Drawer
Чтобы Navigation Drawer еще точнее соответствовал рекомендациям от Google, можно сделать следующие улучшения (см. полный листинг MainActivity в конце статьи):
- Скрывать клавиатуру при открытии NavigationDrawer:
Закрывать NavigationDrawer по нажатию системной кнопки «Назад»:
Реализацию всех этих улучшений вы можете посмотреть в полном листинге MainActivity:
Источник