- NumberPicker
- Пример на Kotlin
- Выбрать кота (Kotlin)
- Android NumberPickers
- What are NumberPickers?
- Creating a NumberPicker
- Setting Custom Values
- Retrieving NumberPicker Values
- Number picker android studio
- Android Number Picker Tutorial
- Android Number Picker Example
- NumberPicker element in xml layout
- Android Number Picker
- Android Number Picker Listener
- NumberPicker Formatter
- Android NumberPicker Material Style
- About
- Number picker android studio
- About
- Number picker android studio
- About
NumberPicker
Компонент NumberPicker находился в разделе Advanced старых версий студии. Компонент позволяет выбрать нужное число из заданного диапазона. Принцип работы похож на револьверный барабан — можно прокручивать числа в одну или другую сторону. Когда будет достигнут заданный предел, то числа продолжат изменяться в заданном диапазоне.
Учитывая, что компонент убрали из студии, можно предположить, что он оказался не очень востребованным.
Разместим компонент на экране.
Несмотря на то, что есть атрибут orientation, толку от него немного. Работает только вертикальный режим.
Добавляем немного кода:
Мы определили максимальное и минимальные числа для нашего вида. Удивительно, но через XML нельзя установить эти значения. Запустив проект, вы можете теперь выбрать нужное число через стрелочки. Недавно проверял на другом телефоне (API 19) — стрелочек уже не было.
Метод setWrapSelectorWheel() с параметром false может отключить бесконечную прокрутку:
Пример на Kotlin
Добавим на экран текстовую метку, чтобы отслеживать текущее выбранное значение.
Выбрать кота (Kotlin)
Мы можем заменить числа на свои значения через метод setDisplayedValues() (Java), например, на имена котов. В этом случае компонент приобретает какой-то смысл.
Про остальные методы почитайте в документации.
Источник
Android NumberPickers
Oct 26, 2018 · 3 min read
In this tutorial you will learn how to create NumberPicker widgets in Android Studio with custom values and how to retrieve NumberPicker values.
What are NumberPickers?
NumberPickers are a widget avalible in Android Studio. They are a set of values selectable by either a horizontal or vertical scrolling wheel.
Creating a NumberPicker
To create a NumberPicker, go to the XML file of your main activity. Switch from the Design tab to the Text tab and type
When y o u switch back to the Design tab, the NumberPicker should be visible. The NumberPicker in the XML will look different from the NumberPicker in the app. Under ID, name the NumberPicker with the what_where_why naming scheme. In this case it will be numberpicker_main_picker. Don’t forget to constrain your NumberPicker! For this example the picker is centered horizontally and vertically.
In your MainActivity, create a NumberPicker variable and wire it to the NumberPicker you created in your XML.
Setting Custom Values
To set custom values on your NumberPicker, first set a minimum and maximum value. In this example we will have 5 values, so we will set the range to:
A NumberPicker takes an array of Strings as its values. First create an instance variable of a string array, then initialize the array with your desired values.
Next, set the NumberPicker values to these Strings with .setDisplayedValues()
When the program is run, it should look like this:
*note: the best way to format this code is to handle it under an initializePicker(); method, then run the method in onCreate. However, for the sake of simplicity in this tutorial, I will not be doing this.*
Retrieving NumberPicker Values
To get the value of your NumberPicker every time it is changed, create an onValueChangeListener in onCreate. In the overriden onValueChange method, create an int variable to store the picker value. Next, make a Log.d to log what the picker value is.
With the code we currently have, the NumberPicker value will be an int. To retrieve the String value of the picker we must access the String array storing our picker values. Rather than just logging the value of picker1, we must log pickerVals[valuePicker1].
Источник
Number picker android studio
Android Number Picker Tutorial
October 09, 2017
In your application, if you need to provide an option of allowing user to select a number from a pre defined range of numbers, then you’ll have to use android NumberPicker widget. Depending on the theme applied, number picker is displayed in different styles.
In this tutorial, topics related to number picker such as using number picker with an example, number picker listener, number picker material style, number picker custom style, and number picker formatter are covered.
Android Number Picker Example
Below example shows how you can use number picker in your application. You need to set range for number picker by setting min and max attributes in xml or calling setMinValue and setMaxValue on NumberPicker object in activity.
NumberPicker element in xml layout
Android Number Picker
Below screen shows number picker when application theme is set to one of the app compact material themes.
Android Number Picker Listener
To listen to current value change of NumberPicker, you need to provide implementation of NumberPicker.OnValueChangeListener interface which has one call back method onValueChange. In this method, you can get user picked or current value of number picker.
You can call setOnValueChangedListener method on number picker object to add value change listener to NumberPicker.
NumberPicker Formatter
You can use number picker formatter to convert number picker values to the desired format, for example, you can use number formatter to display currency.
For that, you need to create an implementation of NumberPicker.Formatter interface. The interface has format method which gets called for each number from the NumberPicker number range and the returned value from this method is what is seen in UI. You can add formatter to NumberPicker by calling setFormatter on number picker object.
Android NumberPicker Material Style
Android introduced material themes in android api level 21. To use material themes and make your app run on previous version of android, you should use app compact themes. For more information on android themes and styles, read android themes and styles tutorial and for material styles, read android material styles and themes tutorial.
Above pictures show NumberPicker in mater style. You can customize number picker material style to change color of selection divider or background as shown below. Since number picker material style Widget.Material.NumberPicker is available from api level 21, if your application needs to run on prior android versions, you need to create version specific style using Widget.NumberPicker number picker style.
About
Android app development tutorials and web app development tutorials with programming examples and code samples.
Источник
Number picker android studio
The android library that provides a simple and customizable NumberPicker. It’s based on android.widget.NumberPicker.
- Customizable fonts(color, size, strikethrough, underline, typeface)
- Customizable dividers(color, distance, length, thickness, type)
- Horizontal and Vertical mode are both supported
- Ascending and Descending order are both supported
- Also supports negative values and multiple lines
attribute name | attribute description | default |
---|---|---|
np_width | The width of this widget. | |
np_height | The height of this widget. | |
np_accessibilityDescriptionEnabled | Flag whether the accessibility description enabled. | enabled |
np_dividerColor | The color of the selection divider. | |
np_dividerDistance | The distance between the two selection dividers. | |
np_dividerLength | The length of the selection divider. | |
np_dividerThickness | The thickness of the selection divider. | |
np_dividerType | The type of the selection divider. | side_lines |
np_fadingEdgeEnabled | Flag whether the fading edge should enabled. | |
np_fadingEdgeStrength | The strength of fading edge while drawing the selector. | |
np_formatter | The formatter of the numbers. | |
np_hideWheelUntilFocused | Flag whether the selector wheel should hidden until the picker has focus. | |
np_itemSpacing | Amount of space between items. | |
np_lineSpacingMultiplier | The line spacing multiplier for the multiple lines. | |
np_max | The max value of this widget. | |
np_maxFlingVelocityCoefficient | The coefficient to adjust (divide) the max fling velocity. | |
np_min | The min value of this widget. | |
np_order | The order of this widget. | ascending |
np_orientation | The orientation of this widget. | vertical |
np_scrollerEnabled | Flag whether the scroller should enabled. | |
np_selectedTextAlign | The text align of the selected number. | center |
np_selectedTextColor | The text color of the selected number. | |
np_selectedTextSize | The text size of the selected number. | |
np_selectedTextStrikeThru | Flag whether the selected text should strikethroughed. | |
np_selectedTextUnderline | Flag whether the selected text should underlined. | |
np_selectedTypeface | The typeface of the selected numbers. | |
np_textAlign | The text align of the numbers. | center |
np_textColor | The text color of the numbers. | |
np_textSize | The text size of the numbers. | |
np_textStrikeThru | Flag whether the text should strikethroughed. | |
np_textUnderline | Flag whether the text should underlined. | |
np_typeface | The typeface of the numbers. | |
np_value | The current value of this widget. | |
np_wheelItemCount | The number of items show in the selector wheel. | |
np_wrapSelectorWheel | Flag whether the selector should wrap around. |
Add the dependency in your build.gradle
Thank you to all our backers! 🙏
The source code is licensed under the MIT license.
About
🎰 The android library that provides a simple and customizable NumberPicker.
Источник
Number picker android studio
A simple customizable NumberPicker for Android.
Add NumberPicker component in your XML layout
Name | Type | Default |
---|---|---|
min | int | 0 |
max | int | 999999 |
value | int | 1 |
unit | int | 1 |
focusable | boolean | false |
custom_layout | layout | @layout/number_picker_layout |
if you want to customize your NumberPicker layout you can create your own.
IMPORTANT! This layout should contains at least 3 items with given Ids:
- Button (@+id/increment)
- Button (@+id/decrement)
- TextView (@+id/display)
Note: You can see an example layout in both sample and library modules.
Example XML layout:
Here is the list of methods with definitions.
Sets minimum value allowed
Gets minimum value
Sets maximum value allowed
Gets maximum value allowed
Sets unit value for increment/decrement operation
Gets unit value
Sets NumberPicker current value
Gets NumberPicker current value
setActionEnabled(ActionEnum action, boolean enabled)
Enables or disables Increment/Decrement buttons
Enables or disables NumberPicker editable via keyboard
NumberPicker will be incremented by defined unit value
NumberPicker will be incremented by given unit value
NumberPicker will be decremented by defined unit vale
NumberPicker will be decremented by given unit value
NumberPicker will be refreshed with already defined value
NumberPicker will lose the focus
Checks whether given value is acceptable or not
This is triggered when you try to set lower or higher than the given min/max limits
This is triggered when the NumberPicker is incremented or decremented.
Note: setValue method will not trigger this listener.
This is triggered when you click «done» button on keyboard after you edit current value.
Note: «done» button can be changed on xml so this listener should be overrided according to new IME option.
This is triggered when clearFocus() is called which helps to set new value when the focus lost
About
A simple customizable NumberPicker plugin for Android
Источник