Skip to main content

android - How to create a color picker dialog

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Color Picker"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.colorpickerexample;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private int mPickedColor = Color.WHITE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        Button btn = (Button) findViewById(R.id.btn);

        // Set the application context
        mContext = getApplicationContext();

        // Set an click listener for Button widget
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Get a GridView object from ColorPicker class
                GridView gv = (GridView) ColorPicker.getColorPicker(MainActivity.this);

                // Initialize a new AlertDialog.Builder object
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

                // Set the alert dialog content to GridView (color picker)
                builder.setView(gv);

                // Initialize a new AlertDialog object
                final AlertDialog dialog = builder.create();

                // Show the color picker window
                dialog.show();

                // Set the color picker dialog size
                dialog.getWindow().setLayout(
                        getScreenSize().x - rl.getPaddingLeft() - rl.getPaddingRight(),
                        getScreenSize().y - getStatusBarHeight() - rl.getPaddingTop() - rl.getPaddingBottom());

                // Set an item click listener for GridView widget
                gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        // Get the pickedColor from AdapterView
                        mPickedColor = (int) parent.getItemAtPosition(position);

                        // Set the layout background color as picked color
                        rl.setBackgroundColor(mPickedColor);

                        // close the color picker
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    // Custom method to get the screen width in pixels
    private Point getScreenSize(){
        WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        //Display dimensions in pixels
        display.getSize(size);
        return size;
    }

    // Custom method to get status bar height in pixels
    public int getStatusBarHeight() {
        int height = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            height = getResources().getDimensionPixelSize(resourceId);
        }
        return height;
    }
}
ColorPicker.java

package com.cfsuman.me.colorpickerexample;

import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
//import android.widget.RelativeLayout.LayoutParams;
//import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView.LayoutParams;
import android.widget.TextView;

import java.util.ArrayList;

public class ColorPicker {
    private Context mContext;
    // GridView column width and TextView width, height in pixels
    private static int columnWidth = 40;

    public ColorPicker(Context context){
        this.mContext = context;
    }

    public static View getColorPicker(Context mContext){
        // Initialize a new GridView widget
        GridView gv = new GridView(mContext);

        // Specify the GridView layout parameters
        gv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        // Define column width and number of columns
        gv.setNumColumns(GridView.AUTO_FIT);
        gv.setColumnWidth(columnWidth); // Should be same as TextView width and height

        // Define addition settings of GridView for design purpose
        gv.setHorizontalSpacing(0);
        gv.setVerticalSpacing(0);
        gv.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
        gv.setBackgroundColor(Color.TRANSPARENT);
        gv.setPadding(5, 5, 5, 5);
        gv.setGravity(Gravity.CENTER);

        // Get the ArrayList of HSV colors
        final ArrayList colors = HSVColors();

        // Create an ArrayAdapter using colors list 
        ArrayAdapter<Integer> ad = new ArrayAdapter<Integer>(mContext, android.R.layout.simple_list_item_1, colors) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                // Cast the current view as a TextView
                TextView view = (TextView) super.getView(position, convertView, parent);

                // Get the current color from list
                int currentColor = (int) colors.get(position);

                // Set the background color of TextView as current color
                view.setBackgroundColor(currentColor);

                // Set empty text in TextView
                view.setText("");

                // Set the layout parameters for TextView widget
                LayoutParams lp = new LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT
                );
                view.setLayoutParams(lp);

                // Get the TextView LayoutParams
                LayoutParams params = (LayoutParams) view.getLayoutParams();

                // Set the TextView width and height in pixels
                // Should be same as GridView column width
                params.width = columnWidth; // pixels
                params.height = columnWidth; // pixels

                // Set the TextView layout parameters
                view.setLayoutParams(params);
                view.requestLayout();

                // Return the TextView as current view
                return view;
            }
        };

        // Specify the GridView data source
        gv.setAdapter(ad);

        // return the GridView
        return gv;
    }

    // Custom method to generate hsv colors list
    public static ArrayList HSVColors(){
        ArrayList<Integer> colors= new ArrayList<>();

        // Loop through hue channel, saturation and light full
        for(int h=0;h<=360;h+=20){
            colors.add(HSVColor(h, 1, 1));
        }

        // Loop through hue channel, different saturation and light full
        for(int h=0;h<=360;h+=20){
            colors.add(HSVColor(h, .25f, 1));
            colors.add(HSVColor(h, .5f, 1));
            colors.add(HSVColor(h, .75f, 1));
        }

        // Loop through hue channel, saturation full and light different
        for(int h=0;h<=360;h+=20){
            //colors.add(createColor(h, 1, .25f));
            colors.add(HSVColor(h, 1, .5f));
            colors.add(HSVColor(h, 1, .75f));
        }

        // Loop through the light channel, no hue no saturation
        // It will generate gray colors
        for(float b=0;b<=1;b+=.10f){
            colors.add(HSVColor(0, 0, b));
        }
        return colors;
    }

    // Create HSV color from values
    public static int HSVColor(float hue, float saturation, float black){
        /*
            Hue is the variation of color
            Hue range 0 to 360

            Saturation is the depth of color
            Range is 0.0 to 1.0 float value
            1.0 is 100% solid color

            Value/Black is the lightness of color
            Range is 0.0 to 1.0 float value
            1.0 is 100% bright less of a color that means black
        */
        int color = Color.HSVToColor(255,new float[]{hue,saturation,black});
        return color;
    }
}




More android examples

Popular posts from this blog

How to use NumberPicker in Android

Table of contentsNumberPicker ExamplesetOnValueChangedListeneronValueChange()setWrapSelectorWheel()setMinValue()setMinValue()setMaxValue()NumberPicker with String ArraysetDisplayedValues()String Array1. NumberPicker Example activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity" android:background="#ffffff" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25dp" android:text="Select a number..." /> <NumberPicker android:id="@+id/np" …

TextView new line (multiline) in android

TextView new line (multiline) TextView display text on android app. by default, TextView show text on a single line, and if it is long then TextView take more lines to display its text. android developers can generate a new line on TextView both programmatically and syntactically. android developers can make a multiline TextView without splitting text to multiline by android:minLines attribute.

the following android example code demonstrate us how can we syntactically create a new line on TextView widget by xml layout file and string resource file.

the simplest way to create a new line on TextView is android:text attribute. android:text attribute allow us to display text on android app. we can add a simple '\n' to TextView text where we want to start a new line. in this way we can create a multiline TextView widget in android app. we can assign android:text attribute value by this way android:text="Line1 \n Line2 \n Line3" for a TextView widget. this value will…

How to change TextView font size in android

TextView font size TextView widget display text on android application. we can set or change TextView font size statically by declarative syntax in xml layout file or programmatically at run time in java file. even we can use an xml file source to define font size.

the following example code demonstrate us how can we define TextView font size in xml layout file and how can we uses dimens.xml to reference font size. in this example we did not changes any coding in java file, so here we only include the layout xml file and dimens.xml file. activity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_margin="25dp" tools:context=".MainActivity" > <TextView android:id=&…