Android statusbar color transparent

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.

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 Полностью прозрачная строка состояния?

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

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

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

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

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

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

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

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

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

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

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

Читайте также:  Начало разработка для android

Работает для 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 не учитывается высота строки состояния. Еще несколько со ссылкой на статью, и у нас есть полностью рабочее решение:

Источник

joinAero / TransparentStatusBarActivity.java

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

xml version = » 1.0 » encoding = » utf-8 » ?>
android .support.v4.widget.DrawerLayout
xmlns : android = » http://schemas.android.com/apk/res/android «
xmlns : app = » http://schemas.android.com/apk/res-auto «
xmlns : tools = » http://schemas.android.com/tools «
android : id = » @+id/drawer «
android : layout_width = » match_parent «
android : layout_height = » match_parent «
android : fitsSystemWindows = » true «
tools : context = » .ui.demo.TransparentStatusBarActivity «
tools : openDrawer = » end » >
android .support.design.widget.CoordinatorLayout
android : layout_width = » match_parent «
android : layout_height = » match_parent «
android : fitsSystemWindows = » true » >
include layout = » @layout/toolbar »/>
android .support.v7.widget.RecyclerView
android : id = » @+id/recycler «
android : layout_width = » match_parent «
android : layout_height = » match_parent «
android : scrollbars = » none «
app : layout_behavior = » @string/appbar_scrolling_view_behavior »/>
android .support.design.widget.CoordinatorLayout>
android .support.design.widget.NavigationView
android : id = » @+id/nav «
android : layout_width = » wrap_content «
android : layout_height = » match_parent «
android : layout_gravity = » end «
android : fitsSystemWindows = » true «
app : headerLayout = » @layout/nav_header_main «
app : menu = » @menu/nav_menu_main »/>
android .support.v4.widget.DrawerLayout>
Читайте также:  Настройка коди плеера андроид

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Источник

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.

Источник

Flutter — Set Status Bar Color, Brightness and Transparency

Do you want to set the color, brightness, and transparency of the status bar when your Flutter application is running in the foreground? Find out in this tutorial.

Operating systems like Android and iOS have a status bar on the top of the screen where the user can see information such as time, battery level, and notifications. Sometimes, changing the appearance of the status bar according to the application theme may result in a better look. If you create an application using Flutter, setting the style of the status bar can be done easily by using AppBar , SystemChrome , or AnnotatedRegion . Below are the examples.

Using AppBar

If your application includes an AppBar at the top, by default the AppBar affects the status bar appearance. Therefore, you can modify the AppBar in order to change the status bar.

Set Color

The color of the AppBar is applied to the status bar by default, with a semi-transparent overlay on the top of the status bar. You can change the color by passing backgroundColor property to the constructor of AppBar .

Читайте также:  2 гис для андроид как пользоваться

Set Brightness

The brightness property of AppBar can be used to set the brightness of SystemUiOverlayStyle . This can be used to set the color of the icons on the status bar. If you set the brightness to Brightness.dark , SystemUiOverlayStyle.light will be used and the color of the icons will be set to light. Otherwise, if you set the brightness to Brightness.light , SystemUiOverlayStyle.dark will be used and the color of the icons will be set to dark. AppBarTheme.brightness will be used if you don’t pass the value.

However, using AppBar ‘s brightness to set SystemUiOverlayStyle is obsolete. You should use systemOverlayStyle instead.

Full Code

Using SystemChrome

There is another way to set the style of the status bar. You can use SystemChrome.setSystemUIOverlayStyle , which is used to set the SystemUiOverlayStyle . While the previous way (using AppBar only works if you have an AppBar on the top, the SystemChrome.setSystemUIOverlayStyle should only be used if you don’t have an AppBar or CupertinoNavigationBar . If you call the static method, the change will persist across all routes in your application. Therefore, if the user navigates to another route, the applied style will not disappear until the SystemChrome.setSystemUIOverlayStyle is called again to override the style.

The method can be called anywhere. If you want to apply the same style to all routes in your application, you can call it inside the main method. If you want to have different styles for each page or route, you need to call the method inside the respective widget. For example, you can put it inside the initState or build method. Beware that using the method along with certain widgets such as AppBar or CupertinoNavigationBar may produce unexpected results since those widget may override the style.

Set Color

The color of the status bar can be set by passing a Color as the statusBarColor argument.

Set Transparency/Opacity

To make the status bar looks transparent, you can set the opacity of the color.

Set Brightness

The brightness of the top status bar icons can be set by passing statusBarIconBrightness whose type is Brightness enum. It only affects Android version M and greater. If you set the value to Brightness.light , the icons color will be set to light. Otherwise, if you set the value to Brightness.dark , the icons color will be set to dark.

For iOS, the brightness of the top status bar can be set by passing the statusBarBrightness argument.

Full Code

Using AnnotatedRegion

Flutter has a generic class named AnnotatedRegion , which is used to annotate a region of the layer tree with a value.

You can set SystemUiOverlayStyle as the generic type ( AnnotatedRegion ). Therefore, you can pass SystemUiOverlayStyle as the value and a widget as the child argument.

The constructor of SystemUiOverlayStyle has some arguments for setting the style of the status bar. You can pass statusBarColor , statusBarBrightness , statusBarIconBrightness . The name, type, and behavior of each argument are the same as the respective argument of SystemChrome.setSystemUIOverlayStyle . Moreover, the applied style also persists when the user navigates to different routes. Using AppBar or CupertinoNavigationBar may also override the style created using AnnotatedRegion .

Set Color

The color of the status bar can be set by passing statusBarColor argument with a Color value.

Set Transparency/Opacity

To make the status bar looks transparent, just set the opacity of the color.

Set Brightness

For Android M and higher, you can pass statusBarBrightness to set the brightness of the status bar icons. If you set the value to Brightness.light , the icons color will be set to light. Otherwise, if you set the value to Brightness.dark , the icons color will be set to dark.

For iOS, setting the top status bar brightness can be done by passing the statusBarIconBrightness argument.

Источник

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