- ProgressBar — Индикатор прогресса
- Основы
- Стилизация
- Индикатор с текстом
- Анимация ObjectAnimator
- Дополнительное чтение
- Circle progress indicator android
- Progress Indicators – Material Components For Android
- Usage of progress indicators
- Showing and hiding progress indicators
- Animation on progress indicators
- Types of progress indicators
- Determinate Linear progress Indicator
- Indeterminate Linear progress Indicator
- Circular indicator
- Types
- Determinate Circle progress Indicator
- Indeterminate Circle progress Indicator
- theming Progress Indicators
- Circle 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 — серия статей на тему создания индикаторов прогресса, ссылка на первую часть.
Источник
Circle progress indicator android
Copy raw contents
Copy raw contents
Android Circle Progress Indicator
This widget is a cutomized version of the Android ProgressBar. It provides developers the ability to add a dynamically populated progress circle with gradient.
- Increase or decrease progress changes
- Modifiable
- Ring width
- Ring background color
- Ring fill color
- Ring gradient
Compatible with all versions of the Android operating system
Including in your project
First declare the JitPack repository:
Then declare the dependency like this:
This tracks against the tag v0.2
Using in Your Project
To use this in your application, just add two progress bars in your layout.xml on top of each other. Set the background on the first one to circle_progress_background, and the background on the second to circle_progress_foreground:
Note: the foreground progress bar android:rotation tag needs to be set to -90 to start the progress at 0
Inside the activity, declare the ProgressBar you’ve defined as the foreground circle, and set it’s progress:
That’s all it takes!
There are a number of easily configurable values that you can override in your project.
Any of the values below can be put into your project and changed to re-configure the Circle Progress Indicator.
- 60dp — This is defines the radius (size) of the circle.
- 7dp — This defines the thickness of the circle ring, where the fill colors are applied.
- @color/dark_blue — This defines the starting color for the gradient that covers the percentage of the progress circle ring that is completed.
- @color/coral_blue — This defines the ending color for the gradient that covers the percentage of the progress circle ring that is completed.
- @color/light_gray and @color/light_gray define the gradient for the remaining section of the progress circle. Note that they are by default set to the same color, which acts as a solid fill color.
The progress ring is defined in /res/drawable/circle_progress_foreground.xml . The developer can override the dimention and color values:
- innerRadius defines the size of the hole inside the ring (in dp)
- thickness defines the width of the bar that goes around the outside of the ring (in dp)
- startColor/endColor defines the beginning and ending colors of the gradient as it travels around the ring
- the operating system transitions the between colors for you
- sweep defines the type of gradient
The developer can also modify the background ring (in this screen shot, the gray ring). It is defined (with same tags) in /res/drawable/circle_progress_background.xml.
Copyright Cardinal Solutions 2016. Licensed under the MIT license.
Источник
Progress Indicators – Material Components For Android
Progress indicators express an unspecified wait time or display the length of a process. Material design provides an implementation of linear and circular progress indicators, compatible back to API 15 .
Progress Indicators is API-compatible with Android’s progressBar class and can therefore be used as a replacement for the progressBar.
Progress Indicators added in material design in 1.3.0. Now its in alpha 02. So you need to include following dependency to work with progress indicator.
Before starting checkout my other post on material design:
Table of Contents
Usage of progress indicators
It can be included in XML layouts, or constructed programmatically:
XML
Kotlin
Showing and hiding progress indicators
use show() method to show the indicator.
use hide() method to hide the indicator.
Animation on progress indicators
GrowMode will have different visual effects to the linear and circular progress indicators.
Types of progress indicators
Material Design offers two visually distinct types of progress indicators:
Linear indicator
Circular indicator
Lets see both progress indicator in detail.
Determinate Linear progress Indicator
operations display the indicator increasing in width from 0 to 100% of the track, in sync with the process’s progress.
The important part is adding style for the progress indicator.
For determinate linear progress we need to add,
style to create programatically:
Also, we need to set the progress attribute based on the process level.
android:progress=”70″ or progressIndicator.progress = 70.
Adding Determinate Linear progress Indicator using XML,
Programatically using kotlin,
Indeterminate Linear progress Indicator
Indeterminate progress indicators move along a fixed track, growing and shrinking in size.
Adding style for the progress indicator.
For indeterminate linear progress we need to add,
style to create programatically:
Adding Indeterminate Linear progress Indicator using XML,
Programatically using kotlin,
Circular indicator
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.
Types
Circle progress indicators support both determinate and indeterminate operations.
Determinate
Indeterminate
Determinate Circle progress Indicator
operations display the indicator increasing in width from 0 to 100% of the circle.
The important part is adding style for the progress indicator.
For determinate circle progress we need to add,
style to create programatically:
Also, we need to set the progress attribute based on the process level.
android:progress=”70″ or progressIndicator.progress = 70.
Adding Determinate circle progress Indicator using XML,
Programatically using kotlin,
Indeterminate Circle progress Indicator
Indeterminate progress indicators move along a fixed track, growing and shrinking in size in circle shape.
The important part is adding style for the progress indicator.
For indeterminate circle progress we need to add,
style to create programatically:
Also, we need to set the progress attribute based on the process level.
android:progress=”70″ or progressIndicator.progress = 70.
Adding Indeterminate circle progress Indicator using XML,
Programatically using kotlin,
theming Progress Indicators
Linear progress indicators are composed of two required elements:
1. Track
The track is a fixed width rule, with set boundaries for the indicator to travel along.
2. Indicator
The indicator animates along the length of the track.
trackColor — Used to set the color for the circle / linear progress track.
indicatorColor — Used to set the color for the circle / linear progress indicator.
indicatorWidth — Used to change the indicator width for both linear / circle indicators.
Thanks for reading.
Please provide your feedback in comments. Also, share if you like it.
You can download this example in GITHUB.
Источник
Circle progress indicator android
Android Circle Progress Indicator
This widget is a cutomized version of the Android ProgressBar. It provides developers the ability to add a dynamically populated progress circle with gradient.
- Increase or decrease progress changes
- Modifiable
- Ring width
- Ring background color
- Ring fill color
- Ring gradient
Compatible with all versions of the Android operating system
Including in your project
First declare the JitPack repository:
Then declare the dependency like this:
This tracks against the tag v0.2
Using in Your Project
To use this in your application, just add two progress bars in your layout.xml on top of each other. Set the background on the first one to circle_progress_background, and the background on the second to circle_progress_foreground:
Note: the foreground progress bar android:rotation tag needs to be set to -90 to start the progress at 0
Inside the activity, declare the ProgressBar you’ve defined as the foreground circle, and set it’s progress:
That’s all it takes!
There are a number of easily configurable values that you can override in your project.
Any of the values below can be put into your project and changed to re-configure the Circle Progress Indicator.
- 60dp — This is defines the radius (size) of the circle.
- 7dp — This defines the thickness of the circle ring, where the fill colors are applied.
- @color/dark_blue — This defines the starting color for the gradient that covers the percentage of the progress circle ring that is completed.
- @color/coral_blue — This defines the ending color for the gradient that covers the percentage of the progress circle ring that is completed.
- @color/light_gray and @color/light_gray define the gradient for the remaining section of the progress circle. Note that they are by default set to the same color, which acts as a solid fill color.
The progress ring is defined in /res/drawable/circle_progress_foreground.xml . The developer can override the dimention and color values:
- innerRadius defines the size of the hole inside the ring (in dp)
- thickness defines the width of the bar that goes around the outside of the ring (in dp)
- startColor/endColor defines the beginning and ending colors of the gradient as it travels around the ring
- the operating system transitions the between colors for you
- sweep defines the type of gradient
The developer can also modify the background ring (in this screen shot, the gray ring). It is defined (with same tags) in /res/drawable/circle_progress_background.xml.
Copyright Cardinal Solutions 2016. Licensed under the MIT license.
Источник