- ProgressBar — Индикатор прогресса
- Основы
- Стилизация
- Индикатор с текстом
- Анимация ObjectAnimator
- Дополнительное чтение
- Jetpack Compose Ep:9 — Progress Indicator App
- Progress Indicator
- Circular Progress Indicator
- Attributes of Circular Progress Indicator
- Linear Progress Indicator
- Attributes of Linear Progress Indicator
- Material Design Components Progress Indicator in Android
- What are Progress Indicators?
- Types of Progress Indicators
- Linear progress indicator android
ProgressBar — Индикатор прогресса
Основы
Компонент ProgressBar (Индикатор прогресса) применяется в тех случаях, когда пользователю нужно показать, что программа не зависла, а выполняет продолжительную работу.
Находится в категории Widgets.
Студия предлагает несколько видов индикаторов: ProgressBar и ProgressBar (Horizontal). В свою очередь компонент имеет несколько модификаций и их отличия заложены в стилях, если посмотреть XML-описание компонентов. Стили постоянно меняются, поэтому проще выбрать атрибут style и посмотреть предлагаемые варианты из выпадающего списка на текущий момент.
Методы для работы с ProgressBar:
- setProgress() — устанавливает заданное значение индикатора прогресса;
- getProgress() — возвращает текущее значение индикатора прогресса;
- incrementProgressBy() — устанавливает величину дискретизации приращения значения индикатора;
- setMax() — устанавливает максимальное значение величины прогресса.
Круговые индикаторы Normal, Small и Large можно просто разместить на экране, и они будут бесконечно выводить анимацию вращения без единой строчки кода.
Как правило, «бесконечный» индикатор выводят в нужный момент, а когда задача выполнена, то его скрывают. Видимость можно установить через XML и программно.
В коде используется метод setVisibility()
Сейчас проекты в студии используют Material Design, поэтому цвет индикатора будет соответствовать ресурсу colorAccent.
Можно переопределить цвет, если вы хотите отказаться от этой связи с colorAccent, задав свой стиль.
Подключаем через тему.
Другая настройка связана с Tint — оттенками цвета (Android 5.0).
Стилизация
Если вам не нравится внешний вид стандартных индикаторов, то можете придумать свой. Есть два варианта для реализации этой цели. В первом случае можно подготовить готовый png-файл (spin_custom.png) и поместить его в ресурс, например, в папку res/drawable.
Затем в этой же папке создаём xml-файл spinner_png.xml с таким содержанием:
Теперь в разметке активности можно определять ProgressBar так:
Если запустить проект, то увидим такой индикатор:
В реальности индикатор выглядит немного корявым, подёргиваясь на экране. Кроме того, изображение можно улучшить, уменьшив количество цветов и сократив размер файла.
Второй вариант выглядит предпочтительней. На этот раз мы обойдёмся без графических файлов, а будем использовать только XML-разметку. В этой же папке поместим файл spinner_ring.xml следующего содержания:
Теперь в разметке активности пропишем строки:
Получим следующий результат:
Индикатор с текстом
К сожалению, индикатор не выводит текст во время работы, что не очень удобно. Можно создать свой ProgressBar из TextView или создать свой компонент на основе ProgressBar. Другой простой способ — наложить текстовый блок прямо на индикатор, используя RelativeLayout. Пример для пояснения.
Код, чтобы увидеть работу индикатора. При каждом щелчке кнопки значение индикаторов увеличиваются на 10 процентов.
Индикаторы прогресса также можно использовать в заголовках приложения у старых устройств, а также в ActionBar и ToolBar у новых устройств.
Компонент постоянно дорабатывается. Например, в Android 8 появились новые методы isAnimating(), getMin(), setMin().
Анимация ObjectAnimator
Можно подключить готовую анимацию для визуализации компонента.
Дополнительное чтение
Material ProgressBar — статья про создание собственного индикатора в стиле Material Design
Indeterminate — серия статей на тему создания индикаторов прогресса, ссылка на первую часть.
Источник
Jetpack Compose Ep:9 — Progress Indicator App
Here we will see about Progress Indicator and its types with respect to their attributes.
To get your basic done, do visit to my previous articles which are given below:
Note: In build.gradle(Project Level) file, the compose_version is upgraded to ‘1.0.0-beta01’ and maven() is replaced with mavenCentral(). Also the dependency is upgraded to classpath “com.android.tools.build:gradle:7.0.0-alpha08”
classpath “org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.30”
And in build.gradle(Module Level) file, following dependency is upgraded:
implementation ‘com.google.android.material:material:1.3.0’
implementation ‘androidx.activity:activity-compose:1.3.0-alpha03’
Progress Indicator
Progress Indicator is a component which tells user about the current ongoing process such as downloading, processing, verifying, etc.
In Jetpack Compose, there are two types of Progress Indicators and they are as follows:
Circular Progress Indicator
It is also known as Determinate Circular Progress Indicator. It represents the progress by drawing an arc. The arc ranges from 0 to 360 degrees. It doesn’t contain any kind of default animation. To add some animations on it, we can use ProgressIndicatorDefaults.ProgressAnimationSpec. It is a default animation recommend for it.
Attributes of Circular Progress Indicator
- progress — it is used to represent the ongoing progress by ranging from 0.0(no progress) to 1.0(full progress).
Note: values gets forcefully obtained if they are outside of the given range.
- modifier — it is used to provide modifications by means of padding, fill size, etc.
- color — it is used to color the progress indicator
- strokeWidth — it is used to provide stroke to its width
Linear Progress Indicator
It is also known as Determinate Linear Progress Indicator. It represents the progress by drawing an horizontal shaped straight line. It doesn’t contain any kind of default animation. To add some animations on it, we can use ProgressIndicatorDefaults.ProgressAnimationSpec. It is a default animation recommend for it.
Attributes of Linear Progress Indicator
There is only one change in the Linear Progress Indicator’s attribute and that is as follows:
- backgroundColor — The background color stay visible only unitl the progress of the Linear Progress Indicator gets completed(reaches to very end).
Rest are same as Circular Progress Indicator’s attributes except strokeWidth is not available in Linear Progress Indicator.
Источник
Material Design Components Progress Indicator in Android
Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android applications. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. Material design in Android is one of the key features that attracts and engages the customer towards the application. This is a special type of design, which is guided by Google. So in this article, it has been demonstrated how to use Progress Indicators, their types, and anatomy.
Create an empty activity project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Add Required Dependency
Include google material design components dependency in the build.gradle file. After adding the dependencies don’t forget to click on the “Sync Now” button present at the top right corner.
Note that while syncing your project you need to be connected to the network and make sure that you are adding the dependency to the app-level Gradle file as shown below.
What are Progress Indicators?
Progress indicators are used in android to inform the user about ongoing processes, for example, loading applications, network calls, downloading or uploading files. These communicate the app’s state and inform the user whether they can navigate away from the current session of the app.
Types of Progress Indicators
There are majorly two types of Progress Indicators one is a linear indicator and another is a circular indicator. Have a look at the following image to get the difference. These progress indicators may be Determinate or Indeterminate.
- Determinate indicators inform the user about the definite process, these should be only used when the process rate can be detected.
- Indeterminate indicators inform the user about the indefinite process means the current process is can take an indefinite time to complete.
The Linear Progress indicator Consists of two major components:
- Track: The component which is of fixed width, which sets boundaries for the indicator to travel along.
- Indicator: The component which animates along the track.
Источник
Linear progress indicator android
Progress indicators express an unspecified wait time or display the length of a process.
Contents
Using progress indicators
Before you can use Material sliders, you need to add a dependency to the Material Components for Android library. For more information, go to the Getting started page.
Progress indicators inform users about the status of ongoing processes, such as loading an app, submitting a form, or saving updates. They communicate an app’s state and indicate available actions, such as whether users can navigate away from the current screen.
Note: When displaying progress for a sequence of processes, indicate overall progress rather than the progress of each activity.
A determinate progress indicator can be added to a layout:
An indeterminate progress indicator can be added:
Switching from indeterminate to determinate
Indeterminate progress indicators can smoothly transit to determinate progress indicators by setting the progress programmatically:
Note: Once indeterminate progress indicators are switched to the determinate mode (or initialized as determinate), they can be set back to indeterminate mode via calling the setIndeterminate(true) method.
Making progress indicators accessible
Progress indicators inherit accessibility support from the ProgressBar class in the framework. Please consider setting the content descriptor for use with screen readers.
That can be done in XML via the android:contentDescription attribute or programmatically like so:
Showing/hiding the progress indicator
By default, the progress indicator will be shown or hidden without animations. You can change the animation behaviors via app:showAnimationBehavior (or setShowAnimationBehavior method) and app:hideAnimationBehavior (or setHideAnimationBehavior method).
The modes of behaviors are:
- none (default) — shows/hides the view immediately when the visibility is being changed via show , hide or setVisibility method.
- outward — for the linear type, shows the view by expanding from the baseline (or bottom edge) and hides the view by collapsing to the top edge; for the circular type, shows the view by expanding from the inner edge and hides the view by collapsing to the outer edge.
- inward — for the linear type, shows the view by expanding from the top edge and hides the view by collapsing to the baseline (bottom edge); for the circular type, shows the view by expanding from the outer edge and hides the view by collapsing to the inner edge.
When the hide animation behavior is not none, the visibility of the view will be changed after the animation finishes. Please use setVisibilityAfterHide method to set the target visibility as Visibility.INVISIBLE (default) or Visibility.GONE .
Progress indicators can have rounded corners via app:trackCornerRadius or the setTrackCornerRadius method.
Material Design offers two visually distinct types of progress indicators: 1. linear 2. circular
Only one type should represent each kind of activity in an app. For example, if a refresh action displays a circular indicator on one screen, that same action shouldn’t use a linear indicator elsewhere in the app.
Linear progress indicators
Linear progress indicators display progress by animating an indicator along the length of a fixed, visible track. The behavior of the indicator is dependent on whether the progress of a process is known.
Linear progress indicators support both determinate and indeterminate operations.
- Determinate operations display the indicator increasing in width from 0 to 100% of the track, in sync with the process’s progress.
- Indeterminate operations display the indicator continually growing and shrinking along the track until the process is complete.
API and source code:
The following example shows a determinate linear progress indicator.
The following example shows an indeterminate linear progress indicator.
Multi-color indeterminate animation type
For linear progress indicator, there are two indeterminate animation types:
- disjoint — animates as repeated cycles with two disjoint segments in the same color at a time.
- contiguous — animates as repeated cycles with three adjacent segments in different colors.
Note: There is a minimum requirement of 3 indicator colors to use the contiguous animation. Otherwise, an IllegalArgumentException will be thrown.
Circular progress indicators
Circular progress indicators display progress by animating an indicator along an invisible circular track in a clockwise direction. They can be applied directly to a surface, such as a button or card.
Circular progress indicators support both determinate and indeterminate processes.
- Determinate circular indicators fill the invisible, circular track with color, as the indicator moves from 0 to 360 degrees.
- Indeterminate circular indicators grow and shrink in size while moving along the invisible track.
API and source code:
The following example shows a determinate circular progress indicator.
The following example shows an indeterminate circular progress indicator.
Anatomy and key properties
A progress indicator consists of a track and an indicator.
The following attributes are shared between linear and circular progress indicators:
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Track thickness | app:trackThickness | setTrackThickness getTrackThickness | 4dp |
Indicator color | app:indicatorColor | setIndicatorColor getIndicatorColor | colorPrimary |
Track color | app:trackColor | setTrackColor getTrackColor | indicatorColor at disabledAlpha |
Track corner radius | app:trackCornerRadius | setTrackCornerRadius getTrackCornerRadius | 0dp |
Show animation behavior | app:showAnimationBehavior | setShowAnimationBehavior getShowAnimationBehavior | none |
Hide animation behavior | app:hideAnimationBehavior | setHideAnimationBehavior getHideAnimationBehavior | none |
Delay (in ms) to show | app:showDelay | N/A | 0 |
Min delay (in ms) to hide | app:minHideDelay | N/A | 0 |
Linear type specific attributes
Linear type progress indicators also have the following attributes:
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Indeterminate animation type | app:indeterminateAnimationType | setIndeterminateAnimationType getIndeterminateAnimationType | disjoint |
Indicator direction | app:indicatorDirectionLinear | setIndicatorDirection getIndicatorDirection | leftToRight |
Circular type specific attributes
Circular type progress indicators also have the following attributes:
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Spinner size (outer diameter) | app:indicatorSize | setIndicatorSize getIndicatorSize | 40dp |
Inset | app:indicatorInset | setIndicatorInset getIndicatorInset | 4dp |
Indicator direction | app:indicatorDirectionCircular | setIndicatorDirection getIndicatorDirection | clockwise |
Element | Style |
---|---|
Default linear style | Widget.Material3.LinearProgressIndicator |
Default circular style | Widget.Material3.CircularProgressIndicator |
Medium circular style | Widget.Material3.CircularProgressIndicator.Medium |
Small circular style | Widget.Material3.CircularProgressIndicator.Small |
Extra small circular style | Widget.Material3.CircularProgressIndicator.ExtraSmall |
Default linear style theme attribute: ?attr/linearProgressIndicatorStyle
Default circular style theme attribute: ?attr/circularProgressIndicatorStyle
See the full list of styles and attributes.
Progress indicators support Material theming which can customize color and size.
Theming progress indicators
API and source code:
The following example shows a circular progress indicator with Material Theming.
Implementing progress indicator theming
Use theme attributes and styles in res/values/styles.xml , which applies to all circular progress indicators and affects other components:
Use a default type theme attribute, styles and a theme overlay, which applies to all circular progress indicators but does not affect other components:
Use the style in the layout, which affects only this specific circular progress indicator:
Источник