Android circle progressbar style

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 — серия статей на тему создания индикаторов прогресса, ссылка на первую часть.

Источник

Android circle progressbar style

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.

Источник

Android circle progressbar style

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.

Источник

Android circle progressbar style

September 21, 2017

Android ProgressBar is used to show progress of an operation to users. There are two types of progress bars and for each type android provides material styles.

If total duration it takes to complete an operation is known, the progress bar which is used to show progress of such operation is called determinate progress bar or horizontal progress bar.

If total duration it takes to complete an operation is unknown, the progress bar which is used to show progress of such operation is called indeterminate progress bar or circular progress bar.

In this post, you can find details on progress bar attributes, updating progress bar, progress bar material styles, custom material style, custom progress bar, custom horizontal progress bar, and custom circular or indeterminate progress bar.

Adding Android ProgressBar

To use progress bar, add ProgressBar element to layout xml as shown below. Attribute progress needs to be assigned some value to view progress bar. Details about progress bar attribute will be covered in the following sections.

To define indeterminate ProgressBar (circular progress bar), either set indeterminate attribute to true or use android non horizontal progress bar style. To define determinate ProgressBar (horizontal progress bar), do reverse.

Android ProgressBar Attributes

Some of the important progress bar attributes are described below.

  • progress : is used to set progress value, your program needs to periodically update the progress so that progress bar reflects the progress of the operation it represents.
  • indeterminate : is used to indicate type of progress bar, value true means indeterminate progress.
  • indeterminateDrawable : is used to set drawable for indeterminate progress bar.
  • indeterminateDuration : is used to set animation duration for indeterminate progress bar.
  • indeterminateTint : is used to set tint of indeterminate progress bar progress indicator.
  • progressBackgroundTint : is used to set progress indicator background
  • progressTint : is used to set tint of progress indicator.
  • progressDrawable : is used to set determinate progress bar drawable.
  • min : is used to define minimum value.
  • max : is used to define maximum value.

Android ProgressBar Updating Progress

As the purpose of the progress bar is to show the progress of an operation in your application, your program needs to update the progress bar with progress as it is available or periodically.

Below code shows how to update progress bar with progress, it uses RxJava observable which emits integers with 5 seconds delay. This code needs to be added to a method which handles the operation start event.

Android ProgressBar Material Style Application Level

Above screen shot shows progress bar when one of the material styles is applied to application. You can change progress bar color by setting colorAccent to the desired color as shown below and use it as application theme.

Android ProgressBar Material Styles

Android platform provides several material styles such as Widget.Material.ProgressBar.Horizontal, Widget.Material.ProgressBar, etc, but using app compact material styles provide backward compatibility. App compact material styles are Widget.AppCompat.ProgressBar.Horizontal and Widget.AppCompat.ProgressBar for indeterminate and determinate progress bar respectively.

Custom progress bar style

To set the ProgressBar background color, you can use progressBackgroundTint or colorControlNormal attributes. To set ProgressBar color, you can use progressTint or colorControlActivated. If you use colorControlNormal and colorControlActivated, apply the style to progress bar using theme attribute.

Applying custom style to ProgressBar element

Custom progress bar output

Similarly, you can customize theme for indeterminate progress bar as shown below.

Android ProgressBar Secondary Progress

To show secondary progress, first define color for secondary progress by setting secondaryProgressTint attribute to the desired color.

Then update secondaryProgress with secondary progress value like as shown below.

Android Horizontal ProgressBar Custom Drawable

You can define a drawable as xml resource and use it as custom drawable for horizontal or determinate progress bar.

Custom drawable for horizontal progress bar

Below layer list drawable is an example of custom drawable for horizontal progress bar. The layer list drawable defines three layers. First item is for background, second layer is for secondary progress and third layer is for progress. You need to make sure that android defined ids are used for each item in layer list.

Our example drawable xml for custom horizontal progress bar also uses standard color attributes such as colorControlNormal, colorControlActivated, and colorControlHighlight to set colors of progress bar background, progress, and secondary progress respectively so that color of our custom horizontal progress bar can be customized easily.

Custom style for horizontal or determinate progress bar

Applying custom style and theme to ProgressBar element

Custom horizontal progress bar output

Android Custom Circular or Indeterminate ProgressBar

Circular or indeterminate progress bar can be customized by providing custom drawable. You can define custom drawable as xml resource using layer list, shape and rotate. Our example drawable for indeterminate progress bar defines two rectangles and rotates them.

Custom drawable for indeterminate progress bar

Custom style uses custom drawable for indeterminate progress bar

Applying custom indeterminate progress bar style

Custom indeterminate progress bar output

About

Android app development tutorials and web app development tutorials with programming examples and code samples.

Источник

Читайте также:  Android fill canvas with color
Оцените статью