SeekBar (Слайдер)
SeekBar — это обычный слайдер, когда пользователь может передвигать ползунок пальцем на экране. Ползунок также можно двигать при помощи клавиш-стрелок.
Компонент SeekBar находится в разделе Widgets и наследуется от класса ProgressBar. В Android Studio 3.0 представлен в двух вариантах: SeekBar и SeekBar (Discrete).
Для отслеживания перемещения ползунка SeekBar необходимо реализовать интерфейс-слушатель SeekBar.OnSeekBarChangeListener с методами-заглушками:
- onProgressChanged() — уведомляет об изменении положения ползунка;
- onStartTrackingTouch() — уведомляет о том, что пользователь начал перемещать ползунок;
- onStopTrackingTouch() — уведомляет о том, что пользователь закончил перемещать ползунок
Заготовка для Kotlin (на Java будет ниже в статье).
Создадим новый проект и добавим компоненты SeekBar и TextView:
Напишем код, чтобы в текстовом поле отображалось текущее значение ползунка после того, как пользователь отпустит его.
Ниже представлены вариант на Android 5.0 и старый вариант на Android 2.3 до появления Material Design, чтобы вы видели, как менялся интерфейс.
Меняем задний фон экрана
Усложним пример и будем менять цвет у фона экрана. Добавим на форму три компонента SeekBar:
Напишем код, меняющий значение цвета через значения ползунка:
Кот Рыжик попросил выставить цвет, наиболее подходящий цвету его шкурки. Я решил ему немного польстить:
Дополнительное чтение
patryk1007/ShootingSlider — прикольный слайдер, напоминающий стрельбу из пушки в играх
Источник
Android studio seekbar vertical
This is the source code of an Android library: -=:[ VerticalSeekBar ]:=-
Why would you need it?
«Reinventing the wheel is, most of the time, a bad idea.»
If you’ve ever tried to make a vertical SeekBar work properly, you know this is not the case. 😏
From the moment you apply that android:rotation=»270″ all start to get messy: you cannot set the proper height for the drawable; the width of the bar distorts the width of your drawable; even customizing your interaction with the bar is kind of tricky.
I’ve been through all of this and suddenly I’ve had enough.
Introducing a nicer, redesigned and highly customizable VerticalSeekBar.
- custom progress drawable: apply resources or color gradients
- custom thumb: chose your size, background color, corner radius or even to completely hide it
- view width and drawable width completely separated
- choose how to set your progress (just sliding the thumb, clicking around, or both)
- min and max placeholders
- much more!
Step 1. add the JitPack repository to your ROOT build.gradle at the end of repositories:
Step 2. add the dependency:
Now you can add the view to your layout:
maybe add some attributes. here you got some, we’ll discuss them later
All of them can be also set programmatically.
(Please note: it’s strongly recommended to avoid pre-1.2.0 versions due to inconsistencies compared to this guide)
For Java projects
Someone experienced this InflateException . For those guys, it’s worth noticing that this is a KOTLIN library! The reason why you’re getting an InvocationTargetException is because, in case you’re still on Java, you also have to specify:
on your app module’s build.gradle .
Another solution is just to. migrate to Kotlin guys!
Background and Progress
To set your progress value programmatically:
Do you need a smaller or bigger range? You can change maxValue like this:
Let’s put some color on this view, shall we?
You can set a drawable for the background and a drawable for the progress. If you don’t, default colors will be applied.
For both background and progress you have 3 choices:
- set a start color and an end color, the view will create a gradient for you
- set a drawable resource or color (REMEMBER: this choice has priority on the one before)
- just don’t choose (it’s still a choice anyway 😉 )
Example for the first choice: apply a gradient
Example for the second choice: apply a resource (will eventually override the first one)
Your bar can also have rounded corners.
. and a proper independent width
To set minimum and/or maximum placeholders ( null is a possible value to remove them):
Since v1.1.4 you can also choose placeholders’ position
You can choose between <"inside", "outside", "middle">( «middle» by default)
Programmatically, it will be:
Now about the thumb placeholder 👆
It is child of a androidx.cardview.widget.CardView . You can choose the color tint and the corner radius of the CardView:
You can set your thumb drawable like this:
If you just don’t want to see it:
You can interact with your VerticalSeekBar in two ways:
- sliding the thumb
- tapping on the bar
Both those interactions can be disabled if you like (they are true by default).
For instance, It can be useful to disable sliding in case you need to put the VerticalSeekBar on a ScrollView.
To do so:
Try to change those booleans too see other possibilities!
You have the possibility to set a listener for progress changes:
This is how it will look like using Java:
Still want more?
If this level of customization is not enough, I have one last good news for you: the seekbar layout is ENTIRELY CUSTOMIZABLE!
You can pick the original layout_verticalseekbar.xml and put it in your project’s res/layout folder.
Now you can modify it as you wish; just remember to keep all the original ids! 😉 ( thumbCardView and thumbPlaceholder can be safely removed)
Feel free to checkout and launch the example app 🎡
Also, see where using this library has been the perfect choice:
Make with 💚 by Luca Lorusso, licensed under Apache License 2.0
Thanks for the help to Lopez Mikhael
About
[AndroidLib] A nicer, redesigned and vertical SeekBar for Android 🎛
Источник
Android studio seekbar vertical
In Android, SeekBar is an extension of ProgressBar that adds a draggable thumb, a user can touch the thumb and drag left or right to set the value for current progress.
SeekBar is one of the very useful user interface element in Android that allows the selection of integer values using a natural user interface. An example of SeekBar is your device’s brightness control and volume control.
Important Note: Attribute of a SeekBar are same as ProgressBar and the only difference is user determine the progress by moving a slider (thumb) in SeekBar. To add a SeekBar to a layout (XML) file, you can use the element.
SeekBar code in XML:
Table Of Contents
How To Add Listener To Notify The Changes In SeekBar:
SeekBar.OnSeekBarChangeListener is a listener used as a callback that notifies client when the progress level of seekbar has been changed. This listener can be used for both user initiated changes (in xml file or java class) as well as for programmatic changes.
seekBarInstanceVariable.setOnSeekBarChangeListener(new OnSeekBarChangeListener() – This method is used to notify the user changes/actions in the SeekBar.
Methods Needs To Be Implemented:
In Seek bar for getting changes in progress we need to implement three abstract methods. Below is detail description of these three methods:
1. public void onProgressChanged (SeekBar seekBar, int progresValue, boolean fromUser) –
This listener method will be invoked if any change is made in the SeekBar.
2. public void onStartTrackingTouch(SeekBar seekBar) –
This listener method will be invoked at the start of user’s touch event. Whenever a user touch the thumb for dragging this method will automatically called.
3. public void onStopTrackingTouch(SeekBar seekBar) –
This listener method will be invoked at the end of user touch event. Whenever a user stop dragging the thump this method will be automatically called.
getMax():
We can get the maximum value of the SeekBar programmatically means in java class. This method returns an integer value. Below code will get the maximum value from a Seekbar.
getProgress():
We can get the current progress value from a Seekbar in java class using getProgress() method. This method returns an integer value. Below code is used to get the current progress value from a Seek bar.
Attributes of SeekBar In Android:
Now let’s we discuss important attributes that helps us to configure a SeekBar in xml file (layout).
1. id: id attribute uniquely identify SeekBar.
2. max: max attribute in SeekBar define the maximum it can take. It must be an integer value like 10, 20, 100, 200 etc. We can set the max value in XML file as well as in java class. By default, a SeekBar takes maximum value of 100.
Below we set 150 maximum value for a Seek bar.
Setting max value of SeekBar Progress In Java Class :
3. progress: progress is an attribute of SeekBar used to define the default progress value, between 0 and max. It must be an integer value.
Below we set the 200 max value and then set 50 default progress value.
Setting progress In Java Class :
4. progressDrawable: progress drawable attribute is used in Android to set the custom drawable xml for the progress mode of a seekbar. Progress drawable is used when we need to use a custom progress of a seekbar.
Below we set the custom gradient drawable for the progress mode of a Seekbar.
Step 1: Add this code in activity_main.xml or main.xml
Step 2: Create a new drawable resource xml in drawable folder and name it custom_progress. Here add the below code which creates gradient effect in seekbar.
5. indeterminate: indeterminate is an attribute used in android to enable the indeterminate mode of a seekbar. In this mode a seekbar shows a cyclic animation without an indication of progress. This mode is used in application when we don’t know the amount of work has been done. Here actual progress will be hidden from user.
Below we set the indeterminate to true.
6. background: background attribute of seekbar is used to set the background. We can set a color or a drawable in the background of a Seekbar. We can also set the background color in JAVA class.
Below we set the green color for the background of a Seek bar.
Setting Background of SeekBar In Java class:
7. padding: padding attribute of seekbar is used to set the padding from left, right, top or bottom.
- paddingRight: padding right attribute is used to set the padding from the right side of the Seekbar.
- paddingLeft: padding left attribute is used to set set the padding from the left side of the Seekbar.
- paddingTop: padding top attribute is used to set the padding from the top side of the Seekbar.
- paddingBottom: padding bottom attribute is used to set the padding from the bottom side of the Seek bar.
- Padding: padding attribute is used to set the padding from the all side’s of the Seekbar.
Below we set the 20dp padding from the top of the Seek bar.
8. thumb: thumb attribute is used in seekbar to draw a thumb on a seekbar. We can use an image or a drawable for the thumb.
Below is an example code in which we set a drawable icon for the thumb of the seekbar.
First download the thumb icon from here and save in drawable folder of your project. You can also click on below icon and then download it:
SeekBar Example In Android Studio:
Example 1: In the below example of seekbar in Android we display a simple seekbar by using its different attributes as discussed earlier in this post. We also perform seekbar changed listener event which is used to get the changes in the progress of a seek bar. After getting changes, the changed value of progress is displayed by using a Toast. Below is the download code, final output and step by step tutorial:
Important Note: Don’t miss the 2nd example of Custom SeekBar in Android which is discussed right after this example.
Step 1: Create a new project and name it SeekBarExample
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we open an xml file and add the code for displaying a seekbar by using its different attributes like max, default progress and few more.
Step 3: Open src -> package -> MainActivity.java
In this step we open MainActivity and add the code to initiate the seekbar and then perform seekbar changed listener event for getting the changes in the progress of the seekbar. By using this event listener we set get the current value of a seekbar and when a user stop the tracking touch, the value of progress is displayed by using a Toast.
Custom vertical SeekBar Example In Android Studio:
In the 2nd example of seekbar we displayed a custom vertical seekbar by using its different attributes. Similar to first example we perform seekbar changed listener event which is used in getting the changes done in the progress and then those changed value of progress is displayed by using a Toast.
Step 1: Create a new project and name it SeekBarExample
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we open xml file and add the code for displaying a vertical seekbar by using its different attributes like max, default progress etc. In this xml for displaying a vertical seekbar we used a rotational attribute and set 270 value for that.
Step 3: Create an xml file in drawable -> custom_progress.xml
In this step we create a custom drawable xml for the seek bar. In this xml we create a layer list in which we create an item and then set the gradient colors for our custom seek bar.
Step 4: Open src -> package -> MainActivity.java
In this step we open MainActivity and here we add the code to initiate the vertical seekbar and then perform seek bar changed listener event for getting the changes in the progress of the seek bar. By using this event listener we get the current progress value of a seek bar and when a user stop the tracking touch, that value of progress is displayed by using a Toast.
Источник