Android system bar transparent

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

  1. We need translucency
  2. 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.

Источник

how to make fully Android Transparent Status bar

how to make fully Android Transparent Status bar

Hello readers, You are here because you are interested in making your Android app’s status bar fully transparent as title of this post says android transparent status bar. You can do this from styles.xml or you can do this in JAVA code within an activity.

Why making android transparent status bar from java?

We are doing this from java to avoid multiple changes in style.xml, color.xml etc. By this piece of code we will do everything in 1 place. If you have already tried doing changes in style.xml and got half transparent status bar then your problem will be solved by this method, because it will clear window flag and set new window flag to do its work.

This method will work on Android version above 21, means this will work on devices having Android lollipop and above. On android version 19 and 20 (Android kitkat) fully transparent status bar will not work but we will make status bar Translucent instead. Below is screenshot from 3 devices having android version Jelly Bean, Kitkat and Android N to show you difference.

So lets start :

Open class file of your activity, in my case I’m going to open LoginActivity.java file, and inside onCreate() method paste below code and run your app on Android version 21 or higher to see the changes.

Читайте также:  Rick and morty way back home android

below is java code, but if you are working on kotlin then scroll down to get kotlin code as well.

for kotlin developers

So here is how this method work :

First we will check android version is greater than 19 and less than 21 then we will set translusant status bar. and if android version is greater than 21 then we will set “android transparent status bar”. That’s it now you gave to do this in all your activites, or you can create a BaseActivity having code of “android transparent status bar” and extend all your activity with BaseActivity and you are done.

Источник

Android: Full Screen UI with Transparent Status Bar

Activities, the building block of any Android app. Something so simple, yet so complex. Here we are going to talk about something similar related to activities which looks very simple from the outset but gets complex pretty soon. We will build a full screen layout with transparent status bar. I’m not going to talk about why would you need a full screen layout and in what situations. That’s a topic for another discussion.

However, here’s a simple use-case. If you have ever seen any app with a map(like a ride-hailing app), you would see that the map occupies the space below the status bar as well. The content of the layout other than the map doesn’t overlap with the system bar icons. Doesn’t it look sweet?
So, we are just gonna recreate that UI. Something like these:

Set a theme for the Activity
Let’s start with the basics(i assume you already have created an Activity with a map and some content) and so, let’s set a theme for our activity:

And then apply theme to the activity as usual:

Easy peasy!! Let’s see what we have got.

Make UI fullscreen
Now, let’s get down to the fun part. How to make the layout a full screen layout and set the status bar colour?

Let’s jump right into code, try it out on your device and then let’s get down to understanding what is actually happening:

For lollipop and above devices:

What is a Window?
When you open any standard app, you would see a status bar, a navigation bar, and the actual activity. Each of these components have a different window. Each of these components are given a window to draw themselves into. The activity is given a window where it draws the view hierarchy specified by us. The status bar is given a window where the system draws things like time, battery, notification icons etc. The navigation bar also has a different window where it draws the back button, the home button etc. All these windows on a single screen are managed by WindowManager.

What are these different flags you can apply to a window?
If FLAG_TRANSLUCENT_STATUS is enabled, translucent status bar will be shown which we don’t want. So, we first remove this flag.

FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag tells the system that our window is responsible for drawing the background for system bars.

What is systemUiVisibility?
Using this method, we can control the visibility of the system UI drawn by the system. System UI elements are elements like status bar, naviagtion bar etc. SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN helps keep the content from resizing when the system bars hide and show while going in and out of full screen mode.

I think setStatusBarColor() needs no explanation. However, this API is available on or above API 21.

Problem on marshmallow and above devices:
The system bar icons are all white which may not look good if the general colour scheme in your layout is also light.

How to fix it?
Again, setSystemUiVisibility to the rescue. SYSTEM_UI_FLAG_LIGHT_STATUS_BAR makes sure that the status bar icons are drawn in such a way so that they are fully visible in light mode.

Cool..so, now our status bar looks pretty good on most of the API levels. But but.. what’s up with the Floating Action Button. This guy is overlapping with the system bar icons and this kind of UI makes me as an user uncomfortable. So, let’s fix this:

Shift the content
The actual content of your app layout needs to be shifted down so that it doesn’t overlap with the status bar icons. Ok, what do we need to shift it down? Margin..a marginTop will do. Right?
But now comes the million dollar question. How do we know how much marginTop do we need to give to the content view? There are many ways to do that but i’m going to go with the most definitive approach which has worked for me on a variety of devices.

Читайте также:  Плагин для просмотра android

Window insets to the rescue….
What are window insets?
Window insets gives us the size of system view that we would need here. The system view we are talking of here is the status bar. So, the top window inset would give us the margin that we need to apply to our content.

How to get the insets of your current visible window?

Now, it’s just down to getting the view and setting a marginTop on it equal to the topInset of the window:

View Extensions for reuse
Usually in a large application, things like these are repeated. So, wouldn’t it be better to create a helpful kotlin extension on the Activity which we can call from any activity instead of repeating this code everywhere?

And then all we need to do in any Activity is:

A sample Android app using these concepts can be found here.

Источник

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.

Читайте также:  Поларис офис для андроид для чего

Источник

Android Полностью прозрачная строка состояния?

Я искал документацию, но нашел только это: Ссылка . Что используется, чтобы сделать бар прозрачным ? Я пытаюсь сделать строку состояния полностью прозрачной (как показано на рисунке ниже) и сделать ее обратно совместимой для APK android statusbar

Все, что вам нужно сделать, это установить эти свойства в вашей теме:

Для вашей деятельности / макета контейнера, для которого вы хотите иметь прозрачную строку состояния, необходимо установить следующее свойство:

Как правило, это невозможно выполнить на pre-kitkat, похоже, что вы можете это сделать, но какой-то странный код делает это так .

РЕДАКТИРОВАТЬ: Я бы порекомендовал эту библиотеку: https://github.com/jgilfelt/SystemBarTint для многих элементов управления цветом строки состояния перед леденцом на палочке.

После долгих размышлений я узнал, что ответом на полное отключение прозрачности или любого цвета, помещенного в строку состояния и панель навигации для леденца на палочке, является установка этого флага в окне:

Никакая другая тема не нужна, она производит что-то вроде этого:

Просто добавьте эту строку кода в ваш основной файл Java:

Вы можете использовать внешнюю библиотеку StatusBarUtil :

Добавьте на свой уровень модуля build.gradle :

Затем вы можете использовать следующую утилиту для действия, чтобы сделать строку состояния прозрачной:

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

Самый простой способ добиться этого:

Поместите эти 3 строки кода в styles.xml (v19) ->, если вы не знаете, как это сделать (v19), просто напишите их по умолчанию, styles.xml а затем используйте alt +, enter чтобы автоматически создать его:

А теперь перейдите в ваш MainActivity класс и выведите этот метод из onCreate в классе:

Затем поместите этот код в onCreate метод Activity:

Полностью прозрачная панель состояния и панель навигации

Чтобы нарисовать макет под строкой состояния:

Используйте CoordinatorLayout / DrawerLayout, который уже позаботится о параметре fitsSystemWindows, или создайте свой собственный макет так:

Скриншот:

Вы можете использовать код ниже, чтобы сделать строку состояния прозрачной. Смотрите изображения с красной подсветкой, которая поможет вам определить использование кода ниже

Фрагмент кода Kotlin для вашего приложения для Android

Шаг: 1 Запишите код в методе создания

Шаг 2: Вам нужен метод SetWindowFlag, который описан ниже.

Фрагмент кода Java для вашего приложения для Android:

Шаг 1: Основной код активности

Шаг 2: метод SetWindowFlag

Используйте android:fitsSystemWindows=»false» в вашем топ-макете

Вот расширение в kotlin, которое делает свое дело:

Используя этот код в своем XML, вы сможете увидеть временную шкалу в вашей деятельности:

Есть три шага:

1) Просто используйте этот сегмент кода в свой метод @OnCreate

если вы работаете с фрагментом, вы должны поместить этот сегмент кода в метод @OnCreate своей деятельности.

2) Обязательно установите прозрачность в /res/values-v21/styles.xml:

Или вы можете установить прозрачность программно:

3) В любом случае вы должны добавить сегмент кода в styles.xml

ПРИМЕЧАНИЕ. Этот метод работает только с API 21 и выше.

Вы также можете просмотреть мой пример с анимированным аватаром и анимированным текстом.

Итак, позвольте мне объяснить, как это работает. Я создал собственный вид, реализованный AppBarLayout.OnOffsetChangedListener . Внутри HeadCollapsing Custom View я основал текст и изображение в AppBarLayout.

Затем измените просмотры через рассчитанный процент. Например, как меняется вид текста:

Чтобы определить, когда нужно свернуть изображение, оживить созданный объект Pair

с состояниями: TO_EXPANDED_STATE, TO_COLLAPSED_STATE, WAIT_FOR_SWITCH, SWITCHED

затем создана анимация для аватара с состоянием:

Вы можете попробовать это.

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

Внимательно прочитав статью Антона Хадуцкого, я лучше понял, что происходит.

У меня есть DrawerLayout с ConstraintLayout (т.е. контейнер), который имеет Toolbar , включают в себя для основного фрагмента и BottomNavigationView .

Установка DrawerLayout имея fitsSystemWindows истина не является достаточным, вам необходимо установить как DrawerLayout и ConstraintLayout . Предполагая прозрачную строку состояния, цвет строки состояния теперь совпадает с цветом фона ConstraintLayout .

Тем не менее, включенный фрагмент все еще имеет вставку строки состояния, поэтому анимация другого «полноэкранного» фрагмента поверх элемента не меняет цвет строки состояния.

Немного кода из упомянутой статьи в Activity «s onCreate :

И все хорошо, за исключением того, что теперь Toolbar не учитывается высота строки состояния. Еще несколько со ссылкой на статью, и у нас есть полностью рабочее решение:

Источник

Оцените статью