Slider material design android

Компонент Slider из библиотеки материального дизайна

Началось с небольшой детективной истории — разглядывая сайт Material Design, наткнулся на страницу Sliders. В описании говорилось, что данный компонент доступен для Android и даже дана ссылка на Гитхаб. Меня это немножко удивило, так как я ни разу о нём не слышал. Перехожу по ссылке — на Гитхабе говорится, что компонент пока находится в активной разработке и даны куцые примеры на Java. «В этих ваших интернетах» упоминания о Slider не нашёл. В официальной документации по библиотеке тоже нет никаких упоминаний.

Любопытство взяло верх и я стал самостоятельно копаться.

По своему внешнему виду Slider похож на стандартный Seekbar. Но небольшие отличия есть. Чтобы их увидеть, набросал простой проект. Добавим пару слайдеров на экран, кнопку и посмотрим на компонент в действии.

Я использовал последнюю версию библиотеки.

На всякий случай замечу, что когда я вручную прописал код, то Android Studio отказывалась показывать экран активности в режиме «Design», пришлось перезапускать студию. После этого всё нормализовалось.

Код для класса активности.

Запускаем и смотрим на результат.

Первое что бросается в глаза — мы можем установить несколько ползунков через slider.values. Они ведут себя независимо и не мешают друг другу.

У второго слайдера установлен дискретный режим через атрибут android:stepSize. Можно заметить, что в этом режиме на дорожке появились маленькие точки.

Если нажать на ползунок, то сверху появляется плашка с указанием текущего значения.

Щелчок на кнопке программно установит ползунок в нужном месте у первого слайдера. Учтите, что в нашем случае компонент превратится в тыкву слайдер с одним ползунком, так как мы сбросили список значений, оставив только одно.

У слайдера есть несколько слушателей. Для демонстрации привёл один из них — Slider.OnSliderTouchListener.

Текст на плашке можно менять. Это пригодится, когда используются большие числа. Тогда вместо чисел с большим количеством нулей (миллионы, триллионы и т.д.) можно использовать сокращенные варианты. За это поведение отвечает интерфейс LabelFormatter. Также существует вспомогательный интерфейс BasicLabelFormatter, который уже содержит полезные сокращения больших чисел типа 9.1K вместо 9100.

Давайте немного пошалим и напишем слово из трёх букв.

Новый элемент показался интересным и вполне пригодным для использования в проекте.

Источник

Sliders — Material Component For Android

Sliders used to view and select a value or range from the given slider bar.They’re mainly used for adjusting settings such as volume and brightness, etc.

Sliders can use icons on both ends of the bar to represent a numeric or relative scale. The range of values or the nature of the values, such as volume change, can be communicated with icons.

Sliders add into Material design in library version 1.2.0. So, you need to add 1.2.0 or higher version on material design.

Types of sliders

There are two types of sliders.

  • Continuous Slider
  • Discrete Slider

Also, We have a another slider called range slider.

Lets see about these sliders in detail.

Continuous Slider

Continuous sliders allow us to select any value between the given start and end value.

For example, valueFrom = “0.0” and valueTo=”100.0″ in this case, you can select any values between from and to values like 55.5, 62.0, etc.

defining the slider In the layout,

valueFrom : starting value of the slider.

valueTo : ending value of the slider.

value: setting the initial value of the slider.

Similarly, we can add a RangeSlider in a layout:

Читайте также:  Mango office для android

The RangeSlider has app:values attribute to set the range for the slider. we need to provide the range in arrays.

Values changes Listeners

We can observe the changes of the slider in two different ways.

by using addOnSliderTouchListener, we can observe the sliders start and stop touch position values.

similarly, we can add touch listener for the range slider.

Sliders OnChangeListener notified eveerytime the slider value changes.

Also, OnChangeListener for the RangeSlider.

Discrete Slider

Discrete slider allows user to select an exact value in the given input range.

If you want to slider to be discrete, then you need to add attribute call android:stepSize=”5.0″. This will setup the step between valueFrom and valueTo values based on the stepSize value.

For example, valueFrom = 10.0, valueTo = 50.0 and stepSize = 10.0, then you can able to select values 10.0, 20.0, 30.0, 40.0, 50.0 only.

defining discrete slider in the layout:

Also, we can add discrete in the RangeSlider.

We can observe the discrete slider values change same as continuous slider. Please check value changes Listeners above.

Setup the Slider Label

The label will be shown at the top of the slider thumb after you touch the thumb. Basically, Slider layout holding the current selected value of the slider.

We can change the behavior and label format using the below methods.

app:labelBehavior

You can change how it’s drawn via the app:labelBehavior attribute or setLabelBehavior method.

app:labelBehavior having three different modes.

  • floating (default) — draw the label above the slider view.

LabelFormatter

By using a LabelFormatter you can change the display format of the selected values based on your requirement like 10KG, 12MB, like that.

That can be achieved through the setLabelFormatter method.That can be achieved through the setLabelFormatter method.

In above code, I have rounded the selected values and converted into dollars.

key properties of sliders

A Slider has a four UI elements.

  1. Track
  2. Thumb
  3. Value Label
  4. Tick Mark (only for discrete slider)

Источник

Material Slider

Google released Material Components 1.3.0-alpha02 on 16th July 2020. One component that has received a lot of love in this release is the humble slider. There are some nice additions on top of the basic functionality, and in this post we’ll explore them a little.

A Slider is a useful control for allowing the user to specify values without having to use the keyboard. The basic use case for it is vey similar to the Android Framework SeekBar or the AppCompatSeekBar widgets. For these there are various uses: such as scrubbing to a specific location during audio or video playback; or specifying a value within a given range. However, there are some additional use-cases that Slider provides us, as we’ll see later in this article

We’ll begin by creating a very simple slider control and seeing how it looks and behaves.

Basic Behaviour

Creating a Material Slider is very straightforward:

We specify a range of 0-100 on both controls using the valueFrom and valueTo attributes. Doing this gives us the following behaviours ( AppCompatSeekBar is on top, and Slider is on the bottom):

While these look very similar there are some important differences. Firstly, the Slider is styled using the colours defined within my theme whereas AppCompatSeekBar is using default colours from the AppCompat library. Secondly, the Slider is slightly larger making it a little clearer to the user. Probably the most important difference is the addition of a label to the Slider when the user drags the position. This makes it easier for the user to understand the precise value they are selecting. While we can certainly add a separate View to our layout to display this value, the tooltip label makes the UI less cluttered. We can disable that if it is not required. Adding app:labelBehaviour=»gone» will achieve this.

However there are two other label behaviours. The first is the default that we can see in the previous example – this is app:labelBehaviour=»floating» which floats the label over the view. The other option is app:labelBehaviour=»withinBounds» . This renders the same as floating but the difference is how it affects the size of the Slider . With floating the measured height of the control does not include the label, whereas withinBounds does include the label in the measured height. This can be important depending on whether we want to ensure that the label does not obscure any other controls within our layout.

Читайте также:  Asus me302c прошивка android
Discrete Slider

The variant of Slider that we’ve looked at thus far is known as a continuous Slider. That means that the value it returns can be any value within the range. However there are cases where we may want to limit this. For example, fractional values are returned by this continuous Slider , but we may require the value to be limited to integers or even larger steps. To achieve this we can use a discrete slider – which returns a discrete set of values. We can change a continuous Slider to a discrete one by adding a single attribute:

Источник

Material Design Components Sliders 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 Sliders and Range Sliders in android. Have a look at the following image to get an overview of the discussion.

Step by Step Implementation

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.

Understanding the Sliders

Where it is used?

Sliders are used to view and select a particular value from the range along the bar. These are ideally used in adjusting the screen brightness, volume or applying the image filters. The icons also can be used at the start and at the end or the selected value can be shown, providing elegance and hence increasing the user experience.

Types of Sliders

There are majorly two types of sliders:

  1. Continuous sliders: These types of sliders allow the users to select a value within the specified range.
  2. Discrete sliders: These types of sliders allow the users to select a specific adjusted value within a specified range by referencing its value indicator.

Anatomy of Sliders

The Slider contains the following elements:

  1. Track: Track shows that the range that is available for a user to select from.
  2. Thumb: The Thumb is a position indicator that can be moved along the track, displaying the selected value of its position.
  3. Value Label: This however is optional, shows the numeric value that corresponds with the thumb’s placement.
  4. Tick Mark: This however is optional, Tick marks along a track represent predetermined values that the user can move the sliders to.

Источник

Sliders – Material Component For Android

Sliders used to view and select a value or range from the given slider bar.They’re mainly used for adjusting settings such as volume and brightness, etc.

Читайте также:  Subway surf 4pda android

Sliders can use icons on both ends of the bar to represent a numeric or relative scale. The range of values or the nature of the values, such as volume change, can be communicated with icons.

Sliders add into Material design in library version 1.2.0. So, you need to add 1.2.0 or higher version on material design.

Before starting checkout my other post on material design:

Table of Contents

Types of sliders

There are two types of sliders.

  • Continuous Slider
  • Discrete Slider

Also, We have a another slider called range slider.

Lets see about these sliders in detail.

Continuous Slider

Continuous sliders allow us to select any value between the given start and end value.

For example, valueFrom = “0.0” and valueTo=”100.0″ in this case, you can select any values between from and to values like 55.5, 62.0, etc.

defining the slider In the layout,

valueFrom : starting value of the slider.

valueTo : ending value of the slider.

value: setting the initial value of the slider.

Similarly, we can add a RangeSlider in a layout:

The RangeSlider has app:values attribute to set the range for the slider. we need to provide the range in arrays.

values/arrays.xml:

Values changes Listeners

We can observe the changes of the slider in two different ways.

addOnSliderTouchListener

by using addOnSliderTouchListener, we can observe the sliders start and stop touch position values.

similarly, we can add touch listener for the range slider.

addOnChangeListener

Sliders OnChangeListener notified eveerytime the slider value changes.

Also, OnChangeListener for the RangeSlider.

Discrete Slider

Discrete slider allows user to select an exact value in the given input range.

If you want to slider to be discrete, then you need to add an attribute called android:stepSize=”5.0″. This will setup the step between valueFrom and valueTo values based on the stepSize value.

For example, valueFrom = 10.0, valueTo = 50.0 and stepSize = 10.0, then you can able to select values 10.0, 20.0, 30.0, 40.0, 50.0 only.

Discrete slider

defining discrete slider in the layout:

Also, we can add discrete in the RangeSlider.

We can observe the discrete slider values change the same as a continuous slider. Please check the value changes Listeners above.

Setup the Slider Label

The label will be shown at the top of the slider thumb after you touch the thumb. Basically, the Slider layout holding the currently selected value of the slider.

We can change the behavior and label format using the below methods.

app:labelBehavior

You can change how it’s drawn via the app:labelBehavior attribute or setLabelBehavior method.

app:labelBehavior having three different modes.

floating (default) — draw the label above the slider view.

withinBounds — draw the label within the slider view. So the label height will be include in the slider height.

gone — the label wont display.

LabelFormatter

By using a LabelFormatter you can change the display format of the selected values based on your requirement like 10KG, 12MB, like that.

That can be achieved through the setLabelFormatter method. That can be achieved through the setLabelFormatter method.

In above code, I have rounded the selected values and converted into dollars.

key properties of sliders

A Slider has a four UI elements.

  1. Track
  2. Thumb
  3. Value Label
  4. Tick Mark (only for discrete slider)

Track Attributes

Thumb Attributes

Values Label Attributes

Tick Mark Attributes

Implementing slider theming

Sliders support Material Theming and can be customized in terms of color and typography.

Add all the theme related changes in res/values/styles.xml

Setting slider primary colors

Theming slider Tooltip

Finally, add all the changes into AppTheme to reflect the changes in all the sliders.

You can download my Slider example in Github .

Thanks for the reading.

Please share if you like it.

Also, checkout my other post related to material design.

Источник

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