Introduction

Depending on your application, you might one day need a good color picker.

With Shake Them All! I needed a color picker to select the color of the default skin and default background. I first had a look at the Android API to see if I could find a Dialog that I could use, without success. I then looked at the SDK samples, and found this color picker:

Before

It is nice but quite limited regarding the number of colors available (black and white are missing for instance), so I used it for a while but I soon needed to make my own.

As I’m quite familiar with the Photoshop color picker, I wanted to make one that looked like it and came up with this list of feature:

finally the selected color should be associated to a key to be stored in the SharedPreferences

After

To achieve this, I needed to implement my own custom Dialog (ColorPickerDialog), associated with a custom View (ColorPickerView).

I’m now going to describe the classes and methods, so if you’re in a hurry, you can jump directly to the end of the post where you will find the download link with instructions on how to use the dialog.

Basically, this Dialog first declares a listener Interface that will be used to notify the new selected color to the class that opened it. The constructor then initializes a few variables:

mListener: the listener passed to the constructor

mKey: the key associated to the color (I needed this because I’m using the same Dialog for 2 Preferences – skin color and background color)

mInitialColor: the initial color

mDefaultColor: the default color

The onCreate method declares what to do when the OnColorChangedListener is called: notify the caller, and close (dismiss) the dialog. The method also sets the content view to our custom View, and the title.

ColorPickerView

This one is more complicated… And to be honest I made this a while ago and I won’t be able to explain every line of code

Here are the main methods used in the class. I’ve left some comments in the code which will hopefully help you understand how it works. If not, feel free to ask me in the comments of the post.

Constructor

The constructor initializes an array of colors used in the hue bar (the top bar):

Basically, your PreferenceActivity should implement the OnColorChangedListener interface. Then, you can open the color picker like any dialog by initializing it and calling its show method. Finally, in your listener, you can use your SharedPreference editor to change the value of the preference with the selected color, and commit your changes.

Voilà, this was my first, poor contribution to the wonderful world of Android. I hope this will help some of you, feel free to use, modify, distribute this code, and of course leave your comments there

This is a great color dialog! Unfortunately I have not been able to get it to save the color value after it is chosen. I used the example you have at the end of the post, but it seems that it is incomplete. Can you give me any pointers?