- SeekBar (Слайдер)
- Меняем задний фон экрана
- Дополнительное чтение
- Android studio range seekbar
- About
- Android studio range seekbar
- Android studio range seekbar
- About
- Кастомный UI Slider (SeekBar)
- Шаг 1: Создайте свое изображения Drawables (9-Patch)
- Шаг 2: SeekBar Progress Drawable
- Шаг 3: SeekBar фон Drawable
- Шаг 4: Соберем все в вместе
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 range seekbar
If you are coming from the original repo, it has a new home so if you’re seeing this, you’re probably in the right place.
This library provides a SeekBar similar to the default Android one, but with two thumb controls allowing a range to be selected.
Features and customizations
- Two thumbs allowing a range to be selected
- Supports integer ranges and floating point ranges
- Text indicating the selected min and max values on the bar
- Smoother drag animation
- Ability to initialise from XML, with attributes (only tested for Integer and Double, would not support all the original types that the class supports when initialized programmatically)
- Ability to make the range-seek-bar only use one thumb instead of two, with all other feature remaining; can be set from XML. This makes it more similar to the default android seekbar, but you still benefit from the other features and very smooth animation.
- Text above thumbs can be disabled and colour can be changed
- Custom icons can be used for the thumbs
How to run demo
Should be able to import, build and run in Android Studio or from the command line with gradle. The rangeseekbar-sample shows the available features and customizations in code and XML.
How to use in your own project
Setup as Gradle dependency
Add this in your build.gradle file:
For latest release:
- For the latest work-in-progress snapshot:
Using the latest work-in-progress snapshot also requires including the snapshot repository as a depencency:
The android-range-seek-bar started as a fork of the following project: https://code.google.com/p/range-seek-bar/ under Apache license.
The images are licensed under Creative Commons ( http://creativecommons.org/licenses/by/3.0/ ). The originals are provided in the original project ( https://code.google.com/p/range-seek-bar/ ) and seek_thumb_disabled.png is added by us.
The source code is licensed under the Apache License. A copy of this can be found at http://www.apache.org/licenses/LICENSE-2.0 and has been included in the repository as well.
About
[DEPRECATED] It provides a SeekBar similar to the default Android one, but with two thumb controls allowing a range to be selected, and some other extras as well.
Источник
Android studio range seekbar
Similar to the Android built-in SeekBar, but it allows to edit a values in a range (start, end).
Add the library dependency:
Step 1. Add the JitPack repository to your build file:
Step 2. Add the dependency to your project’s build.gradle file:
To see the list of all the available attributes, see attrs.xml
Copyright (c) 2017 Alessandro Crugnola
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Источник
Android studio range seekbar
The home for this project has moved over to the following repository: https://github.com/anothem/android-range-seek-bar
You can continue using this repo, but new pull requests and issues will not be looked at. For the most up to date and actively maintained version of this project, please head over to the new repository above.
This is a fork of the following project: https://code.google.com/p/range-seek-bar/ under Apache license.
It provides a SeekBar similar to the default Android one, but with two thumb controls allowing a range to be selected, and some other extras as well.
Modifications in fork from original project
Feature additions are:
- Ability to initialise from XML, with attributes (only tested for Integer and Double, would not support all the original types that the class supports when initialized programmatically)
- Ability to make the range-seek-bar only use one thumb instead of two, with all other feature remaining; can be set from XML. This makes it more similar to the default android seekbar, but you still benefit from the other features and very smooth animation.
- Text labels at beginning and end integrated in the RangeSeekBar view itself
- Floating text above the thumbs that shows the value selected by the thumb
- Styling changes — thinner line, the progress bar shows as “disabled” (line grey, buttons grey, no text labels) when the values are at default min/max
- I’ve also added a PixelUtils class that does Px to Dp and Dp to Px conversions.
How to run demo
This repository contains an ant-based Android project which runs a demo app showing off some of the features of the range-seek-bar and ways of utilizing it. You should be able to import and run like any other Android app.
How to use in your own project
Setup as Gradle dependency
Add this in your build.gradle file:
For latest release:
- For the latest work-in-progress snapshot:
Copy/paste relevant files
Copy the following into your own project:
Then you can use this in your layouts, either programmatically instantiating like in DemoActivity or through XML, like in main.xml
The images are licensed under Creative Commons ( http://creativecommons.org/licenses/by/3.0/ ). The originals are provided in the original project ( https://code.google.com/p/range-seek-bar/ ) and seek_thumb_disabled.png is added by us.
The source code is licensed under the Apache License. A copy of this can be found at http://www.apache.org/licenses/LICENSE-2.0 and has been included in the repository as well.
About
It provides a SeekBar similar to the default Android one, but with two thumb controls allowing a range to be selected, and some other extras as well.
Источник
Кастомный UI Slider (SeekBar)
Android слайдер (или SeekBar как его называют в мире Android) является довольно скользким UI елемент, который мы недавно использовали в нашем Call Your Folks! приложении в качестве средства выбора частоты напоминание от одного дня до трех месяцев.
Я расскажу вам о создании кастомизированного seekbar для вашего Android приложения, используя только несколько XML и drawables.
Шаг 1: Создайте свое изображения Drawables (9-Patch)
Перед созданием любого XML drawables убедитесь, что вы создаете изображения drawables (включая один 9-patch drawable) необходимого для фона seekbar. 9-patch drawables будет использоватся в XML drawables ниже.
Создайте следующие drawables и поместить их в папку /res/drawable/
Шаг 2: SeekBar Progress Drawable
Создадите XML-файл для Android SeekBar который будет отображать прогресс, назовите его seekbar_progress_bg.xml и разместите его в папке /res/drawable/
XML выше сначала рисует полупрозрачный, голубой градиент, потом слой с полупрозрачными полосками поверх градиента. Строчка кода android:tileMode=»repeat» относится к полосе (полупрозрачной) картинки внутри вашей папки drawable созданой в Шаге 1.
Для получения дополнительной информации о создании кастомних форм(shape) с помощью XML используйте ресурси Android drawable resources docs, в частности bitmap и shape секции.
Шаг 3: SeekBar фон Drawable
Далее создайте основной drawable для отображения прогресса, это будет назначить drawable для progress и secondaryProgress действий внутри вашего seekbar. Назовите ваш drawable seekbar_progress.xml и разместите его в папке /res/drawable/
Код в теге nine-patch посилается на фоновое изображение создание в Шаге 1, последний блок посилается на drawable создани в Шаге 2.
Шаг 4: Соберем все в вместе
На данный момент, все, что вам нужно сделать, это визвать seekbar_progress drawable когда создаете seekbar
Две последние строчки устанавливают drawables для прогресса и ползунока для SeekBar . @drawable/seekbar_progress drawable созданий в предыдущем шаге.
Источник