Custom Color Picker using Radio Buttons
Last weekend i ran into a problem where i have to create a custom color palette similar to Google Keep. and i didn’t want to use any external dependency. so i have created my own color picker using the radio button.
In Nutshell 👂
- Declare Color String Array in your colors.xml
- Create Drawable resources for the radio button background
- Create Layout files
- Write Java Program for creating the radio buttons programmatically and adding them to the radio group
- Get selected color from the palette by handling onCheckChangedListener
- Declare the Color String array in your colors.xml
Go to res → values → colors.xml and copy the following code. You can declare as many colors you want, but don’t change the format, don’t use @colors/yourcolor inside the item
2. Create Drawable resources for the radio button background
Radio buttons have two different states checked and unchecked. In the un-checked condition, we are showing the circular background with a solid color. and in the checked condition, we are showing circular tick.
- rb_checked_bg.xml → circular tick mark
- rb_unchecked_bg.xml → circular solid background
- color_picker_rb_bg.xml → selector / toggler between checked and unchecked state
Go to res → drawable → right-click and select Drawable Resource File. Create the following three drawable
3. Create Layout Files
- First, we will create a separate layout file containing a radio button as a root view. we will use this layout to inflate radio buttons programmatically inside our radio group. Go to res → layout → right-click → New Layout Resource file and create custom_radio_button.xml
- Now we have to create an empty Radio Group inside our activity_main.xml.
here is the complete code for activity_main.xml
4. Write a Java Program for creating the radio buttons programmatically and adding them to the radio group
This function first fetches the color list from our colors.xml and store it inside our colorPalette[] string array.
Then it loops through the array and creates radio buttons by inflating custom_radio_button.xml view. after creating the Radio Buttons it sets the id and background tint with respected color.
and finally, it adds it into the Radio Group.
(You can find the complete code for MainActivity.java at the end of this page)
5. Get selected color from the palette by handling onCheckChangedListener
First, get the checked radio button id. This id denotes the position of color selected from a color array.
Here is the complete code for MainActivity.java
Thank You for staying this long ❤️
If you find any bugs or have any suggestions , i would love to hear
Please leave a comment and share it with your colleagues.