A color picker and a color preference for use in Android applications.

Overview

HSV-Alpha Color Picker for Android

This library implements a color picker and a color preference for use in Android applications.

Portrait Landscape Preferences

Features

I couldn't find this combination of features in an existing library, which is why I wrote this one:

  • Alpha slider.
  • Text field to copy and paste hex color values.
  • Old and new colors displayed side by side.
  • Optional selection of "no color".
  • Proper behavior when orientation changes.
  • Up-to-date design.

In addition, the Hue-Saturation picker...

  • gives higher hue precision than a square picker of the same size.
  • allows easier selection of pure white than a circular picker.

Demo App

A demo is available on the Play Store. Source code for the app is in the demo_app folder in this repo.

Using the Library

Add the library dependency to your app module's build.gradle:

    dependencies {
        compile 'com.rarepebble:colorpicker:3.0.1'
    }

Add jcenter() to your repository list if it isn't there already.

If using AndroidX, set android.enableJetifier=true in your gradle.properties.

ColorPreference Usage

Add the ColorPreference to your preference screen xml. Don't forget the extra xmlns: declaration if using the custom attributes described below.

    <PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

        <com.rarepebble.colorpicker.ColorPreference
            android:key="simplePreference"
            android:title="@string/pref_title"
            android:defaultValue="#f00"
            />

    </PreferenceScreen>

The above example will store a color with the key "simplePreference" in the default shared preferences. The stored value is an integer color with alpha component (as used throughout Android). To access the saved color in this example (with the same default)...

    PreferenceManager.getDefaultSharedPreferences(context).getInt("simplePreference", 0xffff0000);

The support library preferences require your app to invoke the color picker dialog in your preference fragment's onDisplayPreferenceDialog() function: If the preference is a ColorPreference, call its showDialog() function...

    public void onDisplayPreferenceDialog(Preference preference) {
        if (preference instanceof ColorPreference) {
            ((ColorPreference) preference).showDialog(this, 0);
        } else super.onDisplayPreferenceDialog(preference);
    }

Note: If upgrading from version 2, the above Java snippet is a new requirement in your application.

See the demo source for more context.

XML Preference Attributes

The standard preference attributes apply as normal, including defaultValue, which can be a hex color, as in the example above, or a reference to a color defined elsewhere.

In addition, the following custom attributes may be used. They should be prefixed with the namespace used for res-auto, as in the example below.

colorpicker_selectNoneButtonText

If set, this text will appear on a third button on the color picker dialog. This resets the color setting to the defaultValue if set. If there is no defaultValue, any saved color setting is removed. Apps can use this to implement "no color selected" logic. Use SharedPreference.contains("myOptionalColorKey") to test for that.

colorpicker_noneSelectedSummaryText

This text displays as the preference summary text if no color has been selected.

colorpicker_showAlpha

Set this to false to hide the alpha slider.

colorpicker_showHex

Set this to false to hide the hex value field.

colorpicker_showPreview

Set this to false to hide the color preview field.

Note: colorpicker_defaultColor was removed in version 2, in favour of android:defaultValue. If upgrading, just switch to using android:defaultValue instead.

    <PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

        <com.rarepebble.colorpicker.ColorPreference
            android:key="myOptionalColor"
            android:title="@string/pref_optional_color"
            app:colorpicker_selectNoneButtonText="@string/no_color"
            app:colorpicker_noneSelectedSummaryText="@string/no_color_selected"
            />
    </PreferenceScreen>

There are further examples in the demo app.

ColorPickerView Usage

In many cases, the ColorPreference will be all that's needed, but if you wish to use the ColorPickerView directly, it can be constructed like any other view, either in code or in XML. Set the initial color with setColor() and retrieve the view's current color with getColor():

    final ColorPickerView picker = new ColorPickerView(getContext());
    picker.setColor(0xff12345);
    ...
    final int color = picker.getColor();

Refer to the ColorPreference source for a fuller example.

XML View Attributes

The custom attributes below should be prefixed with the namespace used for res-auto, just like the preference attributes. See the view demo source for an example.

colorpicker_showAlpha

Set to false to hide the alpha slider. (Default is visible.)

colorpicker_showHex

Set to false to hide the hex value field. (Default is visible.)

colorpicker_showPreview

Set to false to hide the color preview field. (Default is visible.)

ColorPickerView methods

public int getColor()

Gets the current color.

public void setColor(int color)

Sets the original color swatch and the current color to the specified value.

public void setColor(int alpha, float hue, float sat, float bri)

Sets the original color swatch and the current color to the specified values.

public void setOriginalColor(int color)

Sets the original color swatch without changing the current color.

public void setOriginalColor(int alpha, float hue, float sat, float bri)

Sets the original color swatch without changing the current color.

public void setCurrentColor(int color)

Updates the current color without changing the original color swatch.

public void setCurrentColor(int alpha, float hue, float sat, float bri)

Updates the current color without changing the original color swatch.

public void showAlpha(boolean showAlpha)

Shows or hides the alpha slider.

public void showHex(boolean showHex)

Shows or hides the hex value field.

public void showPreview(boolean showPreview)

Shows or hides the color preview field.

public void addColorObserver(ColorObserver observer)

Allows an object to receive notifications when the color changes.

Bugs

Please report bugs in the GitHub issue tracker.

License

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Comments
  • Support for AppCompat preferences

    Support for AppCompat preferences

    Hello,

    I am using com.android.support:preference-v7:23.4.0 to implement the preferences screen in my app. Even if I'll set the min SDK to 11, I'll get an error when trying to use your Color Picker: com.rarepebble.colorpicker.ColorPreference cannot be cast to android.support.v7.preference.Preference

    Is there anything I can do to use it in my app?

    Thanks!

    enhancement help wanted 
    opened by alexandrucene 14
  • More documentation on direct usage of ColorPickerView

    More documentation on direct usage of ColorPickerView

    Hi @martin-stone

    I'm using try to use ColorPickerView directly inside a Dialog specifically AlertDialog but the view doesn't look like the one shown in the screenshot on main page.

    P.S: I like your library & I appreciate your work.

    opened by AkshayChordiya 11
  • Color changed listener

    Color changed listener

    I think, this would be nice... Sadly, the observable color is private and has no getter nor does the ColorPickerView have a function to forward an custom color observable...

    enhancement 
    opened by MFlisar 8
  • Adding ColorPickerView causes significant animation lag when starting an activity using makeSceneTransitionAnimation

    Adding ColorPickerView causes significant animation lag when starting an activity using makeSceneTransitionAnimation

    My app uses ActivityOptionsCompat.makeSceneTransitionAnimation() to animate the transition between clicking a card in a RecyclerView to an activity which may or may not contain ColorPickerView depending on the card that's been clicked on. The view has a default visibility of GONE and is set to VISIBLE in OnCreate when required, but this appears to cause a huge amount of lag in the transition animation.

    Example: https://goo.gl/photos/G9ansCwnEVZq9P9q6

    More than happy to provide any code or other information.

    opened by IvanBrazza 6
  • Soft keyboard popups by default

    Soft keyboard popups by default

    Great lib. However in Android 6 the soft keyboard popups when opening com.rarepebble.colorpicker.ColorPreference as the hex field is gaining focus. Is there a way to avoid keyboard?

    opened by aloz77 6
  • Make fields protected instead of private

    Make fields protected instead of private

    Hi Martin,

    I couldn't extend ColorPreference properly without making these fields accessible by changing them from private to protected

    Another user also mentioned this restriction in https://github.com/martin-stone/hsv-alpha-color-picker-android/issues/16

    I also made defaultColor non-final so it is possible to change it programatically.

    Would you consider integrating these changes in to your excellent library?

    Thanks Jon

    opened by jamorham 6
  • Hi Greate Tool. How to fix this issue, xml file not rendering.

    Hi Greate Tool. How to fix this issue, xml file not rendering.

    java.lang.NoClassDefFoundError: com/rarepebble/colorpicker/R$styleable at com.rarepebble.colorpicker.ColorPreference.(ColorPreference.java:47) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at android.preference.GenericInflater.createItem(GenericInflater.java:385) at android.preference.GenericInflater.createItemFromTag(GenericInflater.java:432) at android.preference.GenericInflater.rInflate(GenericInflater.java:483) at android.preference.GenericInflater.rInflate(GenericInflater.java:495) at android.preference.GenericInflater.inflate(GenericInflater.java:327) at android.preference.Preference_Delegate.inflatePreference(Preference_Delegate.java:60) at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:220) at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:426) at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:350) at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:510) at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:498) at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:888) at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:498) at com.android.tools.idea.rendering.RenderTask.access$600(RenderTask.java:72) at com.android.tools.idea.rendering.RenderTask$3.call(RenderTask.java:610) at com.android.tools.idea.rendering.RenderTask$3.call(RenderTask.java:607) at com.android.tools.idea.rendering.RenderService.runRenderAction(RenderService.java:362) at com.android.tools.idea.rendering.RenderTask.render(RenderTask.java:607) at com.android.tools.idea.rendering.RenderTask.render(RenderTask.java:629) at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.doRender(AndroidLayoutPreviewToolWindowManager.java:652) at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.access$1700(AndroidLayoutPreviewToolWindowManager.java:80) at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$7$1.run(AndroidLayoutPreviewToolWindowManager.java:594) at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:152) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:452) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:402) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:137) at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$7.run(AndroidLayoutPreviewToolWindowManager.java:589) at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320) at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310) at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254) at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269) at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227) at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217) at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238) at com.intellij.util.Alarm$Request$1.run(Alarm.java:351) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:724)

    invalid 
    opened by nAkhmedov 6
  • Thumbnail color not refreshed

    Thumbnail color not refreshed

    Step to reproduce:

    1. Open activity with a settings fragment
    2. Go home
    3. Change the preference color via intent/broadcast receiver
    4. Come back home

    The thumbnail shows the old color. Restarting the activity fix the problem. It would be great to have a public method to refresh/invalidate the thumbnail color.

    enhancement 
    opened by baldapps 5
  • Compatibility upto API 14

    Compatibility upto API 14

    Excellent library, it's just what I needed but can you make your library backward compatible to API 14, moreover my project supports API 14.

    Waiting for it.

    enhancement 
    opened by AkshayChordiya 5
  • defaultValue does not work anymore on older devices

    defaultValue does not work anymore on older devices

    I had to update com.rarepebble:colorpicker:2.3.1 to the latest com.rarepebble:colorpicker:2.4.0 due to the bug with Canvas.save().

    After update I found older devices did not show the default color anymore. If I pick a new color it get worked well.

    Looking into the source and debug it I think the problem is the fix which changes how the defaults are read: "Corrected onGetDefaultValue / onSetInitialValue."

    In my xml I have such entry:

    <com.rarepebble.colorpicker.ColorPreference
                android:defaultValue="@color/learningLanguage"
                android:key="simple_mode_learning_lang_background"
                android:title="@string/pref_colors_simple_mode_learning_lang_background" />
    

    in colors.xml: <color name="learningLanguage">#ece7c9</color> how pref UI is inited:

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        public static class ColorsPreferenceFragment extends PreferenceFragment {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                addPreferencesFromResource(R.xml.pref_colors);
                setHasOptionsMenu(true);
    
            }
    

    Should I change my code somehow to make it read the default color or it is the bug and I have to wait for a new version?

    P.S. thank you very much for this great library!

    bug 
    opened by engilyin 4
  • Delay and out of view in landscape

    Delay and out of view in landscape

    First of all, thanks for the project. I am using your project library in my app. There is a delay in opening the picker view after tapping ( I am using your colorpicker in alertdialog). In Alertdialog, I have managed to change its layout from portrait to landscape without destroying the activity (via dialog dismiss and re create), but the view in landscape (whether its created for the 1st time or recreated) goes out of view at bottom. Only the view of main color arc selector goes out a few dps, rest alpha selector and sat selector are fine. I can send you a snapshot if it helps you.

    duplicate 
    opened by kaushalkumar86 4
  • Colors not displaying properly with darkmode

    Colors not displaying properly with darkmode

    Hi,

    I just realized some colors (yellow and green shades) don't display properly when the device is on dark mode. I was going crazy with this, running my project on my phone with dark mode activated, until I ran it on an emulator that is by default in light mode. On the screenshot you can see that the selected color is yellow and it is displaying black. I guess this is not solvable because it is related with how android manages dark mode, and you have nothing to do there, but I wanted to inform of this.

    Screenshot

    opened by RubenXos 2
  • Question: Use of Enter key to confirm HEX colour change

    Question: Use of Enter key to confirm HEX colour change

    Hi,

    Is there any way to turn of/use a function which will enable the use of Enter key on the keyboard to confirm HEX colour change?

    As when the user starts to enter HEX colour value the Buttons on the colour picker are covered by keyboard, so to confirm the colour change user need to minimise the keyboard and then press OK button.

    If the keyboard is open it would be logical to use Enter to confirm the colour change.

    Happy to help with testing.

    Cheers

    vulterey

    Screenshot_20200610-122148

    opened by vulterey 0
  • modification of the demo app

    modification of the demo app

    Dear Mr. martin-stone I found your library mentioned in https://ourcodeworld.com/articles/read/932/top-10-best-android-color-picker-libraries. I was playing with it and I did a modification of the demo app to be capable of being call from another application via Intent+startActivityForResult so the demo is and application in its own capable of receiving "request" and give back the color number. The modifications are not so big, adding a Done button, add the intent-filter to the manifest and the Intent response in the MainActivity. I guess is good idea to put this "demo" (now an app in its own) in the Play Store (and it continues to be a valid demo for your library). If you also thinks it is a good idea send me an email and I'll forward you the zip file with your modified project Regards (daniel.calcoen at gmail.com)

    opened by ghost-from-the-past 0
  • Default button sets a wrong color 888888

    Default button sets a wrong color 888888

    Using colorpicker 2.4.2 with Android 7 device.

    <de.myapp.ColorPickerPref
                    android:defaultValue="#000000"
                    android:key="appLauncherTextColor"
                    android:summary="Select app label color"
                    android:title="Launcher Text Color"
                    app:colorpicker_selectNoneButtonText="Default"
                    app:colorpicker_showAlpha="false" />
    

    Pressing the Default button in the colorpicker dialog box leads to showing 888888 as selected color and the thumbnail on the pref list is colored darkgray.

    Expect setting color to 000000.

    Actually colorpicker is still passing the correct value #000000 back to settings. However the view in the colorpicker dialog box and pref list is misleading.

    opened by aloz77 9
  • Remove padding of color picker layout

    Remove padding of color picker layout

    Hello again, I ran into the problem that the complete color picker has a padding of 16dp that must be considered when aligning other views with the color picker.

    Therefor, I thought about removing the padding. Thus, the users of this library could decide for themselves about the margin.

    Hope you like this modification. --Julian

    opened by JulianEggers 2
Owner
Martin Stone
Martin Stone
Preference subclass that goes into your PreferenceFragment.

IntegrationPreference This library is especially for extension apps developers. Some applications like (Muzei, Series Guide) has extension capabilitie

Said Tahsin Dane 13 Oct 8, 2020
A color picker for Jetpack compose 🎨

Compose Color Picker ?? Color Picker for Jetpack compose A color picker for Jetpack compose ?? Download ?? Working on it ?? Usage ColorPicker { co

mhssn 12 Dec 8, 2022
This is a picker view for android , support linkage effect, timepicker and optionspicker.(时间选择器、省市区三级联动)

Android-PickerView English Document 注意事项、详请使用方式、更新日志等,请查看 Wiki文档 Wiki文档,Wiki文档,Wiki文档 !~ 重要的事情说三遍 对于使用上有任何疑问或优化建议等,欢迎加入QQ群讨论交流技术问题。 交流群1: 387051294(推荐

Bigkoo 13.2k Jan 6, 2023
A file/directory-picker for android. Implemented as a library project.

Note: avoid using as SD-card file picker on Kitkat+ In Kitkat or above, use Android's built-in file-picker instead. Google has restricted the ability

Jonas Kalderstam 711 Dec 27, 2022
Google Calendar Recurrence picker

Android Recurrence Picker Google Calendar Recurrence picker Screenshot Usage Maven / Gradle Maven: <dependency> <groupId>be.billington.calendar.recu

Benoit Billington 240 Nov 29, 2022
GreenDroid is a development library for the Android platform. It makes UI developments easier and consistent through your applications.

#GreenDroid Foreword : This project, initially initiated by me, Cyril Mottier, is not maintained anymore and can be considered as deprecated. As a con

Cyril Mottier 2.6k Jan 4, 2023
A customizable debug screen to view and edit flags that can be used for development in Jetpack Compose applications

Tweaks A customizable debug screen to view and edit flags that can be used for development in Jetpack Compose applications To include the library add

Guillermo Merino Jiménez 4 Jan 14, 2022
GIFView is a library for showing GIFs in applications

GIFView GIFView is a library for showing GIFs in applications. Setup In your project's build.gradle file: allprojects { repositories { ...

Tzlil Gavra 20 Apr 19, 2022
A View on which you can freely draw, customizing paint width, alpha and color, and take a screenshot of the content. Useful for note apps, signatures or free hand writing.

FreeDrawView A View that let you draw freely on it. You can customize paint width, alpha and color. Can be useful for notes app, signatures or hands-f

Riccardo Moro 643 Nov 28, 2022
Android view that allows the user to create drawings. Customize settings like color, width or tools. Undo or redo actions. Zoom into DrawView and add a background.

DrawView Android view that allows the user to create drawings. Draw anything you like in your Android device from simple view. Customize draw settings

Oscar Gilberto Medina Cruz 839 Dec 28, 2022
A material Switch with icon animations and color transitions

Material Animated Switch A material Switch with icon animations and color transitions Sample video: Youtube Material Animated Switch video Sample app:

Adrián Lomas 1.2k Dec 29, 2022
Simple View to change Brush Size, Alpha and Color

BrushView Simple View to change Brush Size, Alpha and Color Screenshots How to install In your build.gradle project allprojects { repositories {

Andres Ruiz 16 Jun 28, 2018
🎨 Android colorpicker for getting colors from any images by tapping on the desired color.

ColorPickerView ?? ColorPickerView implements getting HSV colors, ARGB values, Hex color codes from any image drawables or your gallery pictures by ta

Jaewoong Eum 1.3k Dec 26, 2022
SystemUiController - Android Ui color controller (status bar, navigation bar)

SystemUiController Android system ui color controller (status bar, navigation bar) Download implementation "land.sungbin:systemuicontroller:${version}

Ji Sungbin 8 Dec 3, 2022
⚡️A highly customizable, powerful and easy-to-use alerting library for Android.

Flashbar A highly customizable, powerful and easy-to-use alerting library for Android. Specs This library allows you to show messages or alerts in you

Aritra Roy 1.7k Dec 7, 2022
A simple, customizable and easy to use swipeable view stack for Android.

SwipeStack A simple, customizable and easy to use swipeable view stack for Android. QuickStart Include the Gradle dependency dependencies { compil

Frederik Schweiger 1.5k Dec 30, 2022
Library and example project on how to use the UITableView component

UITableView for Android Usage Installation Android Studio Paste or clone this library into the /libs folder, in the root directory of your project. Cr

Thiago Locatelli 679 Nov 11, 2022
Xamarin.Android provides open-source bindings of the Android SDK for use with .NET managed languages such as C#

Xamarin.Android Xamarin.Android provides open-source bindings of the Android SDK for use with .NET managed languages such as C#. Build Status Platform

Xamarin 1.8k Jan 5, 2023
Useful library to use custom fonts in your android app

EasyFonts A simple and useful android library to use custom fonts in android apps without adding fonts into asset/resource folder.Also by using this l

Vijay Vankhede 419 Sep 9, 2022