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 — серия статей на тему создания индикаторов прогресса, ссылка на первую часть.
Источник
Custom circle progressbar android
A small Android library allowing you to have a smooth and customizable circular ProgressBar like whatsapp and Tez app, it can be use while uploding or downloading file.
I decided to do this because I was really tired to find progressbar like whatsapp and gradient color progressbar and also you can contribute more color style, or new idea to me.
I took reference or take some code from CircleProgress and change it as i need. also add code for set vector image as background and gradient colors.
Add it in your root build.gradle at the end of repositories:
Add the dependency:
You can either simply use the AdCircleProgress widge from this library on a regular ProgressBar .
Simply replace your ProgressBar with AdCircleProgress , and remember to apply corresponding style and attribute for correct behavior.
For example, to create a first AdCircleProgress like whatsapp:
Second AdCircleProgress in which you can change adpgb_finished_stroke_width like below code:
Third AdCircleProgress in which you can change custom:adpgb_inner_drawable means you can change image or vector image in inner circle like below code:
Fourth AdCircleProgress in which you can change custom:adpgb_show_text=»true» means if you want to show progress in percentage like below code:
Fifth AdCircleProgress in which you can add gradient color for progressbar app:adpgb_gradient_color_one=»@color/colorOne» app:adpgb_gradient_color_two=»@color/colorTwo» like below code:
Do not forget to add xmlns:custom custom attr in your root layout :
About
A small Android library allowing you to have a smooth and customizable circular ProgressBar.
Источник
Кастомизация ProgressBar в Android
Периодически возникает потребность заменить стандартный круговой ProgressBar на какой-либо свой.
Обычно визуальное восприятие у людей более обострено, так что сразу приведу пример нескольких вариантов ProgressBar
На хабре обсуждались некоторые ресурсы генерации прелоадеров, можно использовать их для создания изображения, которое в последствии попадет в ProgressBar.
Для кастомизации ProgressBar’a нужно выполнить несколько вполне тривиальных шагов:
1. Создать Android проект
2. Добавить в проект файл, содержащий loader (например res/drawable/loader1.png)
3. Создать файл анимации (например res/drawable/loader1_progress.xml)
- xml version =«1.0» encoding =«utf-8» ? >
- animated-rotate xmlns:android =«schemas.android.com/apk/res/android»
- android:drawable =»@drawable/loader1″
- android:pivotX =«50%»
- android:pivotY =«50%»/>
4. Разместить ProgressBar в Активити и сказать чтобы использовал наш ресурс анимации, созданный на предыдущем шаге (например res/layouts/)
- xml version =«1.0» encoding =«utf-8» ? >
- LinearLayout xmlns:android =«schemas.android.com/apk/res/android»
- android:layout_width =«fill_parent»
- android:layout_height =«fill_parent»
- android:orientation =«vertical» >
- ProgressBar
- android:indeterminateDrawable =»@drawable/loader1_progress»
- android:layout_height =«50dp»
- android:layout_width =«50dp» >
- ProgressBar >
- LinearLayout >
Кроме использования готовых изображений лоадеров, можно также использовать функционал android для создания лоадера вручную (например /res/drawable/custom_progress.xml)
Рассмотрим на примере фигуры кольца. Цвета указаны в формате #aarrggbb, где аа указывает значение альфа (прозрачность).
- xml version =«1.0» encoding =«utf-8» ? >
- animated-rotate xmlns:android =«schemas.android.com/apk/res/android»
- android:pivotX =«50%»
- android:pivotY =«50%» >
- shape android:shape =«ring»
- android:innerRadiusRatio =«5»
- android:thicknessRatio =«6»
- android:useLevel =«false» >
- gradient
- android:type =«sweep»
- android:useLevel =«false»
- android:centerY =«0.10»
- android:startColor =»#0020ffcc»
- android:centerColor =»#8820ffcc»
- android:endColor =»#ff20ffcc»/>
- size android:width =«18dip»
- android:height =«18dip»/>
- shape >
- animated-rotate >
Если у нас имеется несколько изображений одного ProgressBar
то можно воспользоваться следующим способом (например /res/drawable/custom_progress_blue.xml):
Источник
Custom circle progressbar android
This CircularProgressView is a (surprisingly) circular progress bar Android View that is designed to imitate the Material versions of ProgressBar. These versions can be seen on this page of the Material design spec under Circular indicators.
To use CircularProgressView you must add it as a dependency in your Gradle build:
Then add the view to your layout:
That’s all you need! If you don’t want the CircularProgressView to automatically start animating, omit the app:cpv_animAutostart option and start it manually yourself:
Name | Type | Default | Description |
---|---|---|---|
cpv_progress | float | 0 | The current progress of the progress bar. |
cpv_maxProgress | float | 100 | The maximum progress of the progress bar; what’s considered as 100% of the bar. |
cpv_thickness | dimension | 4px | The thickness of the progress bar. |
cpv_color | color | Theme’s accent color. If not available, Material Blue 500 (#2196F3) | The color of the progress bar. |
cpv_indeterminate | boolean | false | Whether this progress bar is indeterminate or not. If indeterminate, the progress set on this view will not have any effect. |
cpv_animDuration | integer | 4000 | The duration of the indeterminate progress bar animation in milliseconds. It is the duration of all «steps» of the indeterminate animation. (Indeterminate only) |
cpv_animSwoopDuration | integer | 5000 | The duration of the initial swoop of the determinate animation. (Determinate only) |
cpv_animSyncDuration | integer | 500 | The duration of the determinate progress update animation. When you use setUpdate(int) , this is how long it takes for the view to finish animating to that progress. (Determinate only) |
cpv_animSteps | integer | 3 | The number of «steps» in the indeterminate animation (how many times it does the loopy thing before returning to its original position). It is recommended to use an odd number, as even numbers of steps look the same after half the number of steps. |
cpv_animAutostart | boolean | false | Whether this progress bar should automatically start animating once it is initialized. |
cpv_startAngle | float | 0 | The starting angle for progress bar. (Determinate only) |
Name | Description |
---|---|
isIndeterminate() | Returns true if the progress bar is indeterminate, false if determinate. |
setIndeterminate(boolean) | Set whether this progress bar is indeterminate or not. Will reset the animation if the value changes |
getThickness() | Gets the thickness of the progress bar. |
setThickness(int) | Sets thickness of the progress bar. |
getColor() | Gets the color of the progress bar. |
setColor(int) | Sets the color of the progress bar. |
getMaxProgress() | Gets the maximum progress of the progress bar. |
setMaxProgress(float) | Sets the maximum progress of the progress bar. |
getProgress() | Gets the current progress of the progress bar. |
setProgress(float) | Sets the current progress of the progress bar. (Will linearly animate the update.) |
startAnimation() | Starts the animation of the progress bar. (Alias of resetAnimation().) |
resetAnimation() | Resets the animation of the progress bar. |
stopAnimation() | Stops the animation of the progress bar. |
addListener(CircularProgressViewListener) | Registers a CircularProgressViewListener with this view. |
removeListener(CircularProgressViewListener) | Unregisters a CircularProgressViewListener with this view. |
A CircularProgressViewListener class is available for listening to some events (as well as a CircularProgressViewAdapter ).
Event | Description |
---|---|
onProgressUpdate(float) | Called when setProgress is called. (Determinate only) |
onProgressUpdateEnd(float) | Called when this view finishes animating to the updated progress. (Determinate only) |
onAnimationReset() | Called when resetAnimation() is called. |
onModeChange(boolean) | Called when you switch between indeterminate and determinate modes. |
CircularProgressView flickers when phone is in battery saving mode
This happens because battery saving mode automatically ends all Animators, but the ones in CPV run in an endless loop. The best way to work around this right now is to use the native ProgressBar for API >21, since that is when the battery saver mode was introduced. See this issue comment on how to accomplish this.
Источник