Круглый progressbar android studio

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

Источник

Кастомизация ProgressBar в Android

Периодически возникает потребность заменить стандартный круговой ProgressBar на какой-либо свой.

Обычно визуальное восприятие у людей более обострено, так что сразу приведу пример нескольких вариантов ProgressBar

На хабре обсуждались некоторые ресурсы генерации прелоадеров, можно использовать их для создания изображения, которое в последствии попадет в ProgressBar.

Для кастомизации ProgressBar’a нужно выполнить несколько вполне тривиальных шагов:

1. Создать Android проект
2. Добавить в проект файл, содержащий loader (например res/drawable/loader1.png)
3. Создать файл анимации (например res/drawable/loader1_progress.xml)

  1. xml version =«1.0» encoding =«utf-8» ? >
  2. animated-rotate xmlns:android =«schemas.android.com/apk/res/android»
  3. android:drawable =»@drawable/loader1″
  4. android:pivotX =«50%»
  5. android:pivotY =«50%»/>

4. Разместить ProgressBar в Активити и сказать чтобы использовал наш ресурс анимации, созданный на предыдущем шаге (например res/layouts/)

  1. xml version =«1.0» encoding =«utf-8» ? >
  2. LinearLayout xmlns:android =«schemas.android.com/apk/res/android»
  3. android:layout_width =«fill_parent»
  4. android:layout_height =«fill_parent»
  5. android:orientation =«vertical» >
  6. ProgressBar
  7. android:indeterminateDrawable =»@drawable/loader1_progress»
  8. android:layout_height =«50dp»
  9. android:layout_width =«50dp» >
  10. ProgressBar >
  11. LinearLayout >

Кроме использования готовых изображений лоадеров, можно также использовать функционал android для создания лоадера вручную (например /res/drawable/custom_progress.xml)
Рассмотрим на примере фигуры кольца. Цвета указаны в формате #aarrggbb, где аа указывает значение альфа (прозрачность).

  1. xml version =«1.0» encoding =«utf-8» ? >
  2. animated-rotate xmlns:android =«schemas.android.com/apk/res/android»
  3. android:pivotX =«50%»
  4. android:pivotY =«50%» >
  5. shape android:shape =«ring»
  6. android:innerRadiusRatio =«5»
  7. android:thicknessRatio =«6»
  8. android:useLevel =«false» >
  9. gradient
  10. android:type =«sweep»
  11. android:useLevel =«false»
  12. android:centerY =«0.10»
  13. android:startColor =»#0020ffcc»
  14. android:centerColor =»#8820ffcc»
  15. android:endColor =»#ff20ffcc»/>
  16. size android:width =«18dip»
  17. android:height =«18dip»/>
  18. shape >
  19. animated-rotate >

Если у нас имеется несколько изображений одного ProgressBar

то можно воспользоваться следующим способом (например /res/drawable/custom_progress_blue.xml):

Источник

Круглый progressbar android studio

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.

Читайте также:  7zipper для андроид что это такое

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.

Источник

Круглый progressbar android studio

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.

Источник

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