Android numberpicker divider color

Android numberpicker divider color

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.

Источник

Changing NumberPicker divider color

Posted by: admin February 23, 2018 Leave a comment

On recent android versions, number pickers use a blue divider when drawn (cf. image below).

I would like to change this color. Is there a working solution? or perhaps a library that package an updated version of NumberPicker that allows customizing the divider color?

I have tried android-numberpicker but I get an error (see below) at runtime due to some code from the library that tries to access to a resource id that does not exist.

Based on this (https://stackoverflow.com/a/20291416/2915480 although it’s about DatePicker) there are several ways:

Write your own NumberPicker without mSelectionDivider and its affiliates or use backported by Vikram. In last case:

    download from lib from github

change drawable in res/drawable-xxx/np_numberpicker_selection_divider.9.png:

  • to transparent (or whatever) .9.png
  • create np_numberpicker_selection_divider.xml shape line resource in res/drawable (with 0dp height or transparent color).

OR remove if (mSelectionDivider != null) branch from onDraw(Canvas) method in NumberPicker.java like here

Use reflection to access private final field mSelectionDivider (details: https://github.com/android/platform_frameworks_base/blob/master/core/java/android/widget/NumberPicker.java) – e.g. see modification here.
I used reflection but it’s not the best solution.

If you want simply to change the color (based on stannums answer):

This worked for me without using the reflection.

Styles.xml (AppTheme is my app theme in the app)

I’m use workaround method

I’m fairly new to Android so bear in mind that this solution may not be a good practice, but I found a (hacky) way to get this effect using only XML / WITHOUT reflection.

I was able to ‘change’ the colors of the dividers on my NumberPickers within a LinearLayout by adding 2 thin, horizontal views to the ViewGroup, and giving them negative layout margins and my desired color for their backgrounds:

Admittedly, I’m not actually changing the color, but adding new lines with my desired color on top of the built-in dividers. Hopefully this helps someone anyway!

You may have to play with the margins, but these settings were perfect for my custom dialog.

I use the below code to change the divider, not directly the color, but you can do that with a png like this.

This solution that I bring you comes from here, but my code is a easy simplification to change the divider and that’s it.

You can use reflection to do the trick. Here is my solution

using this code for evry thing u want do with divider

It’s better to store a private field if you are going to change divider color in future. Like this:

simplest way is to add this attribute in you NumberPicker selector in xml

android – How do I display a CalendarView in an AlertDialog?

Questions: I’m trying to display the CalendarView in an Alert Dialog, but all that shows up is the month/year and the days of the week. These are the contents of the layout file:

How do I convert a PSD design to Android xml?

Questions: Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. Want to improve this question? Update the question so it’s on-topic for Stack Over.

Источник

NumberPicker

Recently in my day job I needed to use a NumberPicker which is a control I have not had reason to use for quite a long time. The experience was quite a frustrating one and in this post we’ll look at some of the issues with it, and some work-arounds.

A NumberPicker is a control for selecting a number from a limited range. It is used within TimePicker but is also a standalone widget in its own right. There are various forms of rendering it which depend on the theme of your app. I’ll focus on the Material-themed variant (shown on the left) which will be used if your app’s theme derives from R.style.Theme_Material (which the Material Components themes do). It is a vertical list of the numbers in the defined range and the user can either swipe on the list to scroll it to the desired number, or they can tap on the areas above and below the dividers to increment or decrement the value. Also they can long press the same ares to perform repeated increment or decrement which will continue until the long press ceases.

NumberPicker first appeared in Android 3.0 (Honeycomb – API 11). The seasoned Android developers reading this will be groaning at the memory of Honeycomb because it was a rushed release to make Android works on larger devices – specifically tablets because Apple had launched the iPad, and Google wanted to be able to compete with that. NumberPicker is actually a sad reflection of the rushed nature of Honeycomb which has never seen much love since.

NumberPicker actually works quite well, albeit with some caveats which we’ll come to shortly, but the real problems arise when we come to try and style it.

The first indication that there are issues with the implementation of NumberPicker is how we define the range of numbers that it will display. This is easy enough using the setMinValue() and setMaxValue() methods, but these are not exposed as XML attributes so we cannot specify them within our XML layouts – we have to set them programmatically. Compare this to a control such as ProgressBar where we can specify the progress range wither programmatically or in the layout XML.

We can also override the actual strings displayed using the setDisplayedValues() method with an array of String s. This enables us to use both a non-contiguous range (such as 5, 10, 15, 20, …) or even text values (such as “Jan”, ‘Feb”, “Mar”, …). This allows for some nice flexibility in how we present things to the user but, once again, we can only do this programmatically. It would be really useful if we were able to specify a string-array resource in XML, but this is not supported.

Things become even trickier when it comes to styling and themeing a NumberPicker . The style that gets applied by default through the Material theme is defined in @style/Widget.Material.NumberPicker and this has a parent of @style/Widget.NumberPicker . This default style is applied through the theme attribute android:numberPickerStyle , so we should be able to create our own style and apply it by overriding android:numberPickerStyle in our theme.

Unfortunately this is hampered by the limited number of styleable attributes that are exposed for NumberPicker . If we take a look at these in the AOSP sources we can see that there are 11 attributes specific to NumberPicker but some of these are private (the ones with the internal prefix). Leaving 6 attributes that we can actually override, which allow some limited control of the divider appearance and positioning, plus the background colour and the drawable used to show the pressed state of the increment and decrement virtual buttons. This is pretty limited.

Источник

Изменение цвета разделителя NumberPicker

В последних версиях Android для выбора числа используйте синий разделитель при рисовании (см. Изображение ниже).

Я хотел бы изменить этот цвет. Есть ли рабочее решение? Или, возможно, библиотеку, в которой установлена ​​обновленная версия NumberPicker, которая позволяет настраивать цвет разделителя?

Я пробовал android–numberpicker, но я получаю сообщение об ошибке (см. Ниже) во время выполнения из-за некоторого кода из библиотеки, которая пытается получить доступ к идентификатору ресурса, которого нет.

Исходя из этого ( https://stackoverflow.com/a/20291416/2915480, хотя речь идет о DatePicker) существует несколько способов:

Напишите свой собственный номерной номер без mSelectionDivider и его аффилированных лиц или используйте обратную связь с помощью Vikram . В последнем случае:

    Скачать из lib из github

Change drawable в res / drawable-xxx / np_numberpicker_selection_divider.9.png:

  • К прозрачному (или что-то еще) .9.png
  • Создайте ресурс строки формы np_numberpicker_selection_divider.xml в res / drawable (с высотой 0dp или прозрачным цветом).

ИЛИ удалите if (mSelectionDivider != null) ветку из метода onDraw (Canvas) в NumberPicker.java, как здесь

Используйте рефлексию для доступа к private final field mSelectionDivider (подробности: https://github.com/android/platform_frameworks_base/blob/master/core/java/android/widget/NumberPicker.java ) – например, см. Здесь модификацию. Я использовал отражение, но это не лучшее решение.

Если вы хотите просто изменить цвет (на основе ответа на stannums):

Я использую метод обхода

И примените его

Я довольно новичок в Android, поэтому имейте в виду, что это решение может быть не очень хорошей практикой, но я нашел (хакерский) способ получить этот эффект, используя только отражение XML / БЕЗ.

Я смог «изменить» цвета разделителей на моем NumberPickers в LinearLayout, добавив 2 тонких горизонтальных представления в ViewGroup и давая им отрицательные макеты и мой желаемый цвет для их фона:

По общему признанию, я фактически не меняю цвет, но добавляю новые строки с моим желаемым цветом поверх встроенных разделителей. Надеюсь, это кому-то поможет!

Возможно, вам придется играть с полями, но эти настройки были идеальны для моего настраиваемого диалога.

Это работало для меня без использования отражения.

Styles.xml (AppTheme – это тема моего приложения в приложении)

Я использую приведенный ниже код, чтобы изменить разделитель, а не непосредственно цвет, но вы можете сделать это с помощью png, как это .

Это решение, которое я приношу вам, происходит отсюда , но мой код – легкое упрощение для изменения разделителя, и все.

Вы можете использовать отражение, чтобы сделать трюк. Вот мое решение

Используя этот код для evry, что вы хотите делать с делителем

Лучше сохранить личное поле, если вы собираетесь менять цвет разделителя в будущем. Как это:

Самый простой способ – добавить этот атрибут в селектор NumberPicker в xml

Источник

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