- SeekBar (Слайдер)
- Меняем задний фон экрана
- Дополнительное чтение
- Android seekbar set seekbar
- Android SeekBar and Custom SeekBar Examples
- Using Android SeekBar
- Android SeekBar Style Application Level
- Android SeekBar Style Individual
- Android SeekBar Event Listener
- Android Custom SeekBar
- SeekBar custom track or progress drawable
- Seek bar custom thumb
- SeekBar custom tickMark
- About
- Android seekbar set seekbar
- How To Add Listener To Notify The Changes In SeekBar:
- Attributes of SeekBar In Android:
- SeekBar Example In Android Studio:
- Custom vertical SeekBar Example In Android Studio:
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 seekbar set seekbar
Android SeekBar and Custom SeekBar Examples
September 23, 2017
Android SeekBar allows user to select a value from the given range of values by providing draggable thumb. SeekBar is a subclass of ProgressBar which is used to show progress of user initiated or backend operations.
In this post, details on how to use android seek bar, material styles, custom material styles, SeekBar event handling, custom seek bar, and seek bar custom track, thumb and tickMark are covered.
Using Android SeekBar
SeekBar can be added to layout using SeekBar element. The important attributes that need to be set are max, progress and layout_width. Using max attribute of SeekBar, you can set maximum value so that user can select a value from the range starting from 0 to the maximum value by dragging seek bar thumb. You can set default selected value by setting value for progress attribute which gets changed as user drags the thumb.
Below example layout xml contains SeekBar.
Android SeekBar Style Application Level
Above screen shot shows SeekBar when application theme is set to Theme.AppCompat.Light. SeekBar can be customized at application level to show different colors for seekbar background and progress by defining custom colors for colorControlNormal and colorControlActivate.
Android SeekBar Style Individual
Android platform provides Widget.Material.SeekBar (App compact version of it is Widget.AppCompat.SeekBar) and Widget.Material.SeekBar.Discrete material styles for SeekBar.
Below screen shot shows the appearance of seek bar with Widget.Material.SeekBar.Discrete theme. Widget.Material.SeekBar.Discrete is available from API level 24.
SeekBar discrete material style output.
You can define custom material style for seekbar by inheriting Widget.AppCompat.SeekBar and setting custom values for attributes such as progressBackgroundTint, progressTint, and colorControlActivated.
Below material style for seekbar customizes seekbar color by setting background, progress, and thumb colors.
Android SeekBar Event Listener
SeekBar events can be handled by implementing SeekBar.OnSeekBarChangeListener and setting it to seek bar by calling setOnSeekBarChangeListener method.
You can implement behavior for three types of events such as progress change, seek bar touch start and touch stop events using SeekBar.OnSeekBarChangeListener by implementing onProgressChanged, onStartTrackingTouch, and onStopTrackingTouch methods.
SeekBar current value or seek bar progress can be obtained in onProgressChanged, as seekbar current value is passed as parameter to this method.
Android Custom SeekBar
Android seekbar can be customized by providing your own drawable for seek bar track (seek bar progress), seek bar thumb and seek bar tick mark.
SeekBar custom track or progress drawable
Below drawable xml can be used as drawable for seekbar progress.
You can apply the custom drawable to seek bar using progressDrawable attribute.
SeekBar custom track output.
Seek bar custom thumb
Below drawable xml can be used as seek bar thumb.
Apply the above thumb drawable to seek bar by setting thumb attribute.
Seekbar custom thumb output.
SeekBar custom tickMark
SeekBar tick mark can be customized by defining a drawable xml and applying it to seek bar using tickMark attribute.
Below xml is a drawable xml for customizing seek bar tickMark.
Applying seekbar custom tickMark drawable.
Seekbar custom tickMark output
About
Android app development tutorials and web app development tutorials with programming examples and code samples.
Источник
Android seekbar set seekbar
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.
Источник