Seekbar android studio kotlin

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

Источник

SeekBar in Kotlin

Android seekBar is a modified version of progressBar that have draggable thumb in which a user can drag the thumb back and forth to set current progress value. We can use seekbar in our android device like Brightness control, volume control etc.

It is one of the important user Interface element which provides the option to select the integer values within the defined range like 1 to 100.

Читайте также:  Gmail не приходят письма андроид

By dragging the thumb in SeekBar, we can slide back and forth to choose a value between minimum and maximum integer value which we defined using android:min and android:max attributes. respectively.

First we create a new project by following the below steps:

Different Attributes of Android SeekBar Widget

XML Attributes Description
android:id Used to uniquely identify the control.
android:thumb Used to set drawable to be used as thumb that can be moved back and forth.
android:thumbTint Used to set tint to apply to the thumb.
android:min Used to specify the minimum value.
android:max Used to specify the maximum value.
android:progress Used to specify the default progress value between 0 and 100.
android:progressDrawable Used to specify drawable mode of the progress.
android:background Used to set background of the specified view.
android:padding Used to set the padding from left, right, top and bottom.

Modify activity_main.xml file

Here, we will add the Seekbar widget in LinearLayout and set its attributes like id, margin etc.

Источник

Android SeekBar – Kotlin Example

Kotlin Android SeekBar

Android SeekBar is kind of an extension to progress bar, with an addition functionality that user can touch the thumb and drag it to change the value.

In this tutorial, we will learn how to include a SeekBar in our main activity layout and read the values when user interacts with the SeekBar.

The following GIF shows how a user can touch the trackbar, and seek it to the left or right of the bar.

SeekBar Code

Following is a quick code snippet to use SeekBar in your layout file and Kotlin file respectively.

By default, the range of progress is [0,100] in steps of 1.

Following is a step by step guide of what is happening in the above code snippet to use SeekBar.

Step 1: Create a SeekBar in layout file.

Step 2: Add OnSeekBarChangeListener to the interface list of your Activity.

Step 3: Set setOnSeekBarChangeListener to the SeekBar.

Step 4: We have to override the following three methods of OnSeekBarChangeListener.

Example – Android SeekBar

Following are the details of the Android Application we created for this example.

Application Name SeekBarExample
Company name tutorialkart.com
Minimum SDK API 21: Android 5.0 (Lollipop)
Activity Empty Activity

You may keep rest of the values as default and create Android Application with Kotlin Support.

activity_main.xml

MainActivity.kt

Output

Conclusion

In this Android Tutorial : Android SeekBar – Kotlin Example, we have learnt to use SeekBar with an example Android Application.

Источник

Android SeekBar in Kotlin with Examples

In this tutorial, we are creating an Android SeekBar in Kotlin with examples. Seekbar is an Android UI widget element. SeekBar is very similar to progress bar but a user can drag it manually.

You might have noticed such draggable progress bar in music applications where a user can change the song progress by dragging the progress bar with a thumb.

There are two different kind of Seekbars in Android.

  • Plain or Smooth Seekbar: It is smooth seekbar without any discrete points. The default value is from 0 to 100.
  • Discrete Seekbar: This seekbar has discrete progress points. In discrete seekbar we have to provide discrete style using the style property style=»@style/Widget.AppCompat.SeekBar.Discrete»

Android SeekBar Kotlin Example

First of all let’s set the Seekbar widgets inside the activity_main.xml

activity_main.xml

Some of the XML properties that are used in activity_main.xml

XML Attribute Description
android:max Max limit of the seekbar values
android:progress Default progress value

MainActivity.kt

The SeekBar.OnSeekBarChangeListener interface provides these three methods.

  • onProgressChanged: Constantly provides you feedback about progress change.
  • onStartTrackingTouch: Notify the user when the user starts changing the seek bar.
  • onStopTrackingTouch: Get called when the user leaves the progress bar after changing the progress.

onStopTrackingTouch we are showing the progress as a Toast message.

Run the app to see the result.

Now it is your creativity when you use Kotlin Android seekbar. You can use it in music players and video players. There are can multiple use cases.

Источник

Android SeekBar using Kotlin

Android Tutorial

In this tutorial, we’ll discuss and implement SeekBar in our Android Application using Kotlin.

What is Android SeekBar?

SeekBar is a UI element that is an extension of the ProgressBar.

SeekBar adds a draggable thumb to the ProgressBar. It is commonly used in music apps to provide volume control.

SeekBar is like a scale with an upper and lower limit and every step is a single unit.

SeekBar XML Attributes

Some of the important XML attributes of SeekBar are:

  • android:minWidth/maxWidth/minHeight/maxHeight : these attributes are used to set the dimensions of the seekbar view. They don’t change the thickness of the SeekBar.
  • android:max/min : The upper/lower limit of the SeekBar. The android:min is available from Android SDK 26 and above.
  • android:progress : The current value of the thumb position.
  • android:progressTint : Here we pass the color for the progress to the left of the thumb position.
  • android:progressBackgroundTint : This color is displayed for the SeekBar background, to the right of the thumb.
  • android:thumb : Here we can pass a custom drawable that will act as the thumb of the seek bar.
  • android:thumbTint : color of the thumb.
  • android:thumbOffset : The distance between the thumb and the current progress in dp . A negative value shifts the thumb to the right of the progress. A positive one shifts it to the left.
  • style : it’s used to set custom/predefined styles on the SeekBar. There is a popular seekbar style – “Discrete” – which breaks the progress into discrete intervals.
  • android:tickMark : Here we pass a drawable, which acts as breakpoints on the SeekBar. The number of breakpoints/tickMarks is equal to android:max.
  • android:tickMarkTint : used to set a color on the tickMark drawable.
  • android:splitTrack : This expects a boolean value. By default on Android Lollipop and above this is true. It splits the Seekbar track into two parts – left and right of the SeekBar. This isn’t always visible in white background activities.

Creating SeekBar in Kotlin

We can implement the SeekBar.OnSeekBarChangeListener interface to create SeekBar programatically. We have to implement the following three Kotlin functions.

SeekBar Examples

Let’s look at the different types of SeekBar by setting the above properties.

1. Simple SeekBar

2. SeekBar with Progress Tint Color

3. SeekBar with Thumb Tint Color And Offset

4. SeekBar with TickMarks

The tickmark.xml drawable is given below.

5. SeekBar with Custom Style

Here we set Discrete style with different intervals (max value).

6. SeekBar with Split Track

The first one has a Split track enabled by default. The second one does not.

Android SeekBar Kotlin Project Structure

1. Activity XML Code

The code for the activity_main.xml layout is as follows.

We’ve created a custom thumb in the last SeekBar.

2. Activity Kotlin Code

The Kotlin code for the MainActivity.kt class is as follows.

In the above code, we’ve created a SeekBar in Kotlin and added it to the LinearLayout.

Источник

Читайте также:  Defender 2 для андроида
Оцените статью