Sunday, 30 June 2013

Return values from custom popup window to activity

We can return values from custom popup window to activity using listener. Example code:

popup.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#cdcdcd"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="50dp" >

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp" />

    <EditText
        android:id="@+id/bank_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="3dp"
        android:hint="Name"
        android:inputType="textCapWords" />

    <EditText
        android:id="@+id/bankacc_no"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="3dp"
        android:hint="Number"
        android:inputType="number" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10dp" >

        <Button
            android:id="@+id/popupSave"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="10dp"
            android:text="Save" />

        <Button
            android:id="@+id/popupClose"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="10dp"
            android:text="Cancel" />
    </LinearLayout>

</LinearLayout>


Popup.java
package com.example.popupwindow;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;

public class Popup extends PopupWindow {

Context context;
EditText et_name, et_number;
String name, number;

private int dx;
private int dy;
private OnSubmitListener mListener;

public Popup(Context ctx, OnSubmitListener listener) {
super(ctx);

context = ctx;
mListener = listener;

setContentView(LayoutInflater.from(context).inflate(R.layout.popup, null));
setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
View popupView = getContentView();
setFocusable(true);

Button btn_close = (Button) popupView.findViewById(R.id.popupClose);
Button btn_submit = (Button) popupView.findViewById(R.id.popupSave);
et_name = (EditText) popupView.findViewById(R.id.bank_name);
et_number = (EditText) popupView.findViewById(R.id.bankacc_no);

btn_submit.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
String name = et_name.getText().toString();
String number = et_number.getText().toString();

mListener.valueChanged(name, number);//To change the value of the textview of activity.
dismiss();
}
});

btn_close.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {
dismiss();
}
});

// setOnTouchListener is to add drag and drop the popup window.
// If you didn't want, you can remove it.
popupView.setOnTouchListener(new OnTouchListener() {

public boolean onTouch(View arg0, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {

case MotionEvent.ACTION_DOWN:
dx = (int) motionEvent.getRawX();
dy = (int) motionEvent.getRawY();
break;

case MotionEvent.ACTION_MOVE:
int x = (int) motionEvent.getRawX();
int y = (int) motionEvent.getRawY();
int left = (x - dx);
int top = (y - dy);
update(left, top, -1, -1);
break;
}
return true;
}
});
}

public void show(View v) {
showAtLocation(v, Gravity.CENTER, 0, 0);
}

public interface OnSubmitListener {
void valueChanged(String name, String number);
}
}


main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"   
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Number" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showPopup"
        android:text="Change" />

</LinearLayout>


To change the text of textview we have to implement OnSubmitListener in our activity.

Also I have added my custom toast as DialogToast here. This toast message will disappear when you touch the screen and also when this custom toast message appears screen will goes to dim to view the toast message to user perfectly. If you didn't want just change the line to normal toast message or else you can remoe it.

CustomPopupWindowActivity.java
package com.example.popupwindow;

import com.example.popupwindow.Popup.OnSubmitListener;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class CustomPopupWindowActivity extends Activity implements OnSubmitListener {

Context context;
Popup popup;

TextView mTextView1, mTextView2;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mTextView1 = (TextView) findViewById(R.id.textView1);
mTextView2 = (TextView) findViewById(R.id.textView2);

context = this;
popup = new Popup(context, this);
}

public void showPopup(View v) {
popup.show(v);
}

@Override
public void valueChanged(String name, String number) {
mTextView1.setText(name);
mTextView2.setText(number);
new DialogToast(context, "Values updated").show();//For custom toast. You can change or remove this line.
}
}

Sample screen shot of this code.



Thank You



Saturday, 22 June 2013

Dialog as Toast message in Android


What is toast message?

         In Adnroid, Toast is a notification message that pop up and display a cirtain amount of time.

What is drawback toast message?

         Toast message should displayed cirtain amount of time. We can not interrupt it within the time. For example if we set a toast message to display five seconds, we can not hide it within two or three seconds. Tha is main drawback of Toast message.

How to avercome this drawback?

         We can use Dialog as toast message in android. There is two main advantages by using Dialog as Toast message.
        1. We can hide the Toast message any time by touching the screen.
        2. While dispaly Toast message the background will goes to dim. So user can read the toast message without interruption of other views.

DialogToast.java

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

public class CustomToast extends Dialog {
 public CustomToast(Context context, String text) {
  super(context);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  LayoutInflater inflater = (LayoutInflater) context
  .getSystemService(android.content.Context.
     LAYOUT_INFLATER_SERVICE);

  View layout = inflater.inflate(R.layout.toast, null);
  TextView tv = (TextView) layout.findViewById(R.id.toastText);
  tv.setText(text);  
  setContentView(layout);
  show();
  setCanceledOnTouchOutside(true);
  setCancelable(true);
  Window window = getWindow();
  window.setGravity(Gravity.BOTTOM);
  new Handler().postDelayed(new Runnable() {

   public void run() {
    dismiss();
   }
  }, 2500);
 }
}


toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/toastText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000" />

</LinearLayout>


How to call this Dialog as Toast message?
         Following will allow you to display the Dialog as Toast message.
new CustomToast(activity, "Custom Toast").show();

Sample code to calling this Dialog as Toast message.

DialogToastActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class DialogToastActivity extends Activity {
 
 Activity activity;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        activity = this;     
    }
    public void mButtonClick(View v){
     new CustomToast(activity, "Custom Toast").show();
    }
}

Screen shot.



Thank You



Thursday, 20 June 2013

Drawing Example in Android

Simple drawing example in android.

In Android You can draw using Canvas. First You have to get the touched points to draw. By using onTouchEvent method You can get the touched points from android device. Our onTouchEvent method will be

public boolean onTouchEvent(MotionEvent event) {
   PathWithPaint pp = new PathWithPaint();
   if (event.getAction() == MotionEvent.ACTION_DOWN) {
    path.moveTo(event.getX(), event.getY());
    path.lineTo(event.getX(), event.getY());
   } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
    path.lineTo(event.getX(), event.getY());
   } else if (event.getAction() == MotionEvent.ACTION_UP) {
    path.lineTo(event.getX(), event.getY());
    mCanvas.drawPath(path, mPaint);
    pp.setPath(path);
    pp.setmPaint(mPaint);
    _graphics1.add(pp);
   }
   invalidate();
   return true;
  }

Now You are going to draw on the touched point. You have to override the onDraw method to draw on the path. The onDraw method will be like as following
  @Override
  public void onDraw(Canvas canvas) {

   canvas.drawBitmap(mBitmap, 0, 0, mPaint);

   if (_graphics1.size() > 0) {
    canvas.drawPath(_graphics1.get(_graphics1.size() - 1).getPath(), _graphics1.get(_graphics1.size() - 1).getmPaint());
   }
  }


You can use ColorPicker to get different colors.

Also you can save our drawing as .JPG file using FileOutputStream. Also you can erase previously drawn path and clear the whole drawing. And also you can set border.

Complete Code.

MainActivity.java
package com.example.draw;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;

import com.example.draw.ColorPicker.OnColorChangedListener;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ComposePathEffect;
import android.graphics.CornerPathEffect;
import android.graphics.DiscretePathEffect;
import android.graphics.EmbossMaskFilter;
import android.graphics.LinearGradient;
import android.graphics.MaskFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity implements OnColorChangedListener {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  setContentView(R.layout.activity_main);
  
  float[] outerR = new float[] { 12, 12, 12, 12, 0, 0, 0, 0 };
  RectF inset = new RectF(6, 6, 6, 6);
  float[] innerR = new float[] { 12, 12, 0, 0, 12, 12, 0, 0 };
  
  mDrawables = new ShapeDrawable[2];
  
  mDrawables[0] = new ShapeDrawable(new RoundRectShape(outerR, inset, null));
  mDrawables[0].getPaint().setShader(makeSweep());
  
  mDrawables[1] = new ShapeDrawable(new RoundRectShape(outerR, inset, innerR));
  mDrawables[1].getPaint().setShader(makeLinear());
  
  PathEffect mPathEffect1 = new DiscretePathEffect(10, 4);
  PathEffect mPathEffect2 = new CornerPathEffect(4);
  
  mDrawables[0].getPaint().setPathEffect(new ComposePathEffect(mPathEffect2, mPathEffect1));
  LinearLayout layout = (LinearLayout) findViewById(R.id.myDrawing);
  layout.setBackgroundDrawable(mDrawables[0]);
  activity = this; 
  mView = new DrawingView(this);
  layout.addView(mView, new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
  
  init();
  
  mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);
  mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);
 }

 private static Shader makeLinear() {
  return new LinearGradient(0, 0, 50, 50, new int[] { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF }, null, Shader.TileMode.MIRROR);
 }

 private static Shader makeSweep() {
  return new SweepGradient(150, 25, new int[] { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFFFF0000 }, null);
 }

 private ShapeDrawable[] mDrawables;
 private MaskFilter mEmboss;
 private MaskFilter mBlur;
 private Paint mPaint;
 Activity activity;
 View mView;

 private void init() {
  mPaint = new Paint();
  mPaint.setDither(true);
  mPaint.setColor(0xFFFFFF00);
  mPaint.setStyle(Paint.Style.STROKE);
  mPaint.setStrokeJoin(Paint.Join.ROUND);
  mPaint.setStrokeCap(Paint.Cap.ROUND);
  mPaint.setStrokeWidth(3);
 }

 class DrawingView extends View {
  private Path path;
  private Bitmap mBitmap;
  private Canvas mCanvas;
  int width, height;

  public DrawingView(Context context) {
   super(context);
   path = new Path();
   mBitmap = Bitmap.createBitmap(820, 480, Bitmap.Config.ARGB_8888);
   mCanvas = new Canvas(mBitmap);
   this.setBackgroundColor(Color.BLACK);
  }

  private ArrayList<PathWithPaint> _graphics1 = new ArrayList<PathWithPaint>();

  public boolean onTouchEvent(MotionEvent event) {
   PathWithPaint pp = new PathWithPaint();
   if (event.getAction() == MotionEvent.ACTION_DOWN) {
    path.moveTo(event.getX(), event.getY());
    path.lineTo(event.getX(), event.getY());
   } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
    path.lineTo(event.getX(), event.getY());
   } else if (event.getAction() == MotionEvent.ACTION_UP) {
    path.lineTo(event.getX(), event.getY());
    mCanvas.drawPath(path, mPaint);
    pp.setPath(path);
    pp.setmPaint(mPaint);
    _graphics1.add(pp);
   }
   invalidate();
   return true;
  }

  @Override
  public void onDraw(Canvas canvas) {

   canvas.drawBitmap(mBitmap, 0, 0, mPaint);

   if (_graphics1.size() > 0) {
    canvas.drawPath(_graphics1.get(_graphics1.size() - 1).getPath(), _graphics1.get(_graphics1.size() - 1).getmPaint());
   }
   
   Display display = getWindowManager().getDefaultDisplay();
   int width = 300;
   int height = 425;
   try {
    Method mGetRawH = Display.class.getMethod("getRawHeight");
    Method mGetRawW = Display.class.getMethod("getRawWidth");
    width = (Integer) mGetRawW.invoke(display);
    height = (Integer) mGetRawH.invoke(display);
   } catch (SecurityException e) {
    e.printStackTrace();
   } catch (NoSuchMethodException e) {
    e.printStackTrace();
   } catch (IllegalArgumentException e) {
    e.printStackTrace();
   } catch (IllegalAccessException e) {
    e.printStackTrace();
   } catch (InvocationTargetException e) {
    e.printStackTrace();
   }

   int x = 0;
   int y = 0;
   if (curveDrawable == 1) {
    mDrawables[0].setBounds(x, y, x + width, (y + height) - 35);
    mDrawables[0].draw(canvas);
   }
   if (curveDrawable == 2) {
    mDrawables[1].setBounds(x, y, x + width, (y + height) - 35);
    mDrawables[1].draw(canvas);
   }
  }

  public void clearView() {
   _graphics1.removeAll(_graphics1);
   mBitmap = Bitmap.createBitmap(width, height,
     Bitmap.Config.ARGB_8888);
   mCanvas = new Canvas(mBitmap);
   path = new Path();
   invalidate();
  }

  @Override
  public void invalidate() {
   super.invalidate();
  }

  @Override
  protected void onSizeChanged(int w, int h, int oldw, int oldh) {
   super.onSizeChanged(w, h, oldw, oldh);
   width = w;
   height = h;
   mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
   mCanvas = new Canvas(mBitmap);
  }

  public void colorChange() {
   path = new Path();
   invalidate();
  }

  public void saveAsJpg(File f, View v, boolean setWallpaper) {
   String fname = f.getAbsolutePath();
   FileOutputStream fos = null;
   try {
    fos = new FileOutputStream(fname);
    Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
      Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    v.draw(c);
    
    if (setWallpaper) {
     WallpaperManager myWallpaperManager = WallpaperManager
       .getInstance(getApplicationContext());
     try {
      myWallpaperManager.setBitmap(b);
     } catch (IOException e) {
      e.printStackTrace();
     }
     Toast.makeText(activity, "Wallpaper has been seted up",
       Toast.LENGTH_LONG).show();
    } else {
     b.compress(CompressFormat.JPEG, 100, fos);
     Toast.makeText(activity, "Image Saved", Toast.LENGTH_LONG)
       .show();
    }
   } catch (Exception ex) {
    Toast.makeText(activity, "Error Saving Image",
      Toast.LENGTH_LONG).show();
    Log.i("DAVE", "stacktrace is " + ex);
   }
  }
 }

 private boolean isDrawBorder = true;
 int bgcolor = Color.BLACK;

 public void colorChanged(String key, int color) {
  
  if (key.equals("")) {
   mPaint = new Paint();
   mPaint.setDither(true);
   mPaint.setColor(color);
   mPaint.setStyle(Paint.Style.STROKE);
   mPaint.setStrokeJoin(Paint.Join.ROUND);
   mPaint.setStrokeCap(Paint.Cap.ROUND);
   mPaint.setStrokeWidth(3);
  } else if (key.equals("Bg Color")) {
   if (isDrawBorder)
    ((DrawingView) mView).invalidate();
   else
    ((DrawingView) mView).clearView();
   ((DrawingView) mView).setBackgroundColor(color);
   bgcolor = color;
   isDrawBorder = false;
  }

 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  super.onCreateOptionsMenu(menu);

  menu.add(0, 0, 0, "Color").setShortcut('3', 'c');
  menu.add(0, 1, 0, "BG Color").setShortcut('3', 'c');
  menu.add(0, 2, 0, "Emboss").setShortcut('4', 's');
  menu.add(0, 3, 0, "Blur").setShortcut('5', 'z');
  menu.add(0, 4, 0, "Erase").setShortcut('5', 'z');
  menu.add(0, 5, 0, "SrcATop").setShortcut('5', 'z');
  
  SubMenu border = menu.addSubMenu(0, 9, 0, "Border");
  
  menu.add(0, 6, 0, "Set as Wallpaper").setShortcut('5', 'z');
  menu.add(0, 7, 0, "Save").setShortcut('5', 'z');
  menu.add(0, 8, 0, "Clear").setShortcut('5', 'z');

  border.add(0, 10, 0, "Curve").setShortcut('5', 'z');
  border.add(0, 11, 0, "Rectangle").setShortcut('5', 'z');
  border.add(0, 12, 0, "No Border").setShortcut('5', 'z');

  return true;
 }

 private int curveDrawable = 1;

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {

  File myDir = new File(Environment.getExternalStorageDirectory(),
    "Drawings");
  myDir.mkdirs();
  Date now = new Date();
  String fname = "image" + now.getDate() + now.getSeconds() + ".jpg";
  File file = new File(myDir, fname);

  switch (item.getItemId()) {
  
  case 0:
   ((DrawingView) mView).colorChange();
   new ColorPicker(activity, this, "", Color.BLUE, Color.WHITE).show();
   return true;
   
  case 1:
   new ColorPicker(activity, this, "Bg Color", Color.BLUE, Color.WHITE).show();
   return true;
   
  case 2:
   if (mPaint.getMaskFilter() != mEmboss) {
    mPaint.setMaskFilter(mEmboss);
   } else {
    mPaint.setMaskFilter(null);
   }
   return true;
   
  case 3:
   if (mPaint.getMaskFilter() != mBlur) {
    mPaint.setMaskFilter(mBlur);
   } else {
    mPaint.setMaskFilter(null);
   }
   return true;
   
  case 4:
   ((DrawingView) mView).colorChange();
   mPaint = new Paint();
   mPaint.setDither(true);
   mPaint.setColor(bgcolor);
   mPaint.setStyle(Paint.Style.STROKE);
   mPaint.setStrokeJoin(Paint.Join.ROUND);
   mPaint.setStrokeCap(Paint.Cap.ROUND);
   mPaint.setStrokeWidth(13);
   return true;
   
  case 5:
   mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
   mPaint.setAlpha(0x80);
   return true;
   
  case 6:
   ((DrawingView) mView).saveAsJpg(file, mView, true);
   return true;
   
  case 7:
   ((DrawingView) mView).saveAsJpg(file, mView, false);
   return true;
   
  case 8:
   ((DrawingView) mView).clearView();
   return true;
   
  case 10:
   isDrawBorder = true;
   colorChanged("Bg Color", bgcolor);
   curveDrawable = 1;
   return true;
   
  case 11:
   isDrawBorder = true;
   colorChanged("Bg Color", bgcolor);
   curveDrawable = 2;
   return true;
   
  case 12:
   isDrawBorder = true;
   colorChanged("Bg Color", bgcolor);
   curveDrawable = 0;
   return true;
   
  }
  return super.onOptionsItemSelected(item);
 }
}

PathWithPaint.java
package com.example.draw;

import android.graphics.Paint;
import android.graphics.Path;

public class PathWithPaint {
 private Path path;

 public Path getPath() {
  return path;
 }

 public void setPath(Path path) {
  this.path = path;
 }
 
 private Paint mPaint;
 
 public Paint getmPaint() {
  return mPaint;
 }

 public void setmPaint(Paint mPaint) {
  this.mPaint = mPaint;
 } 
}


Sample screen shot of this application


Simple Drawing example in Android



Thank You


Saturday, 15 June 2013

Simple ColorPicker for android.

Sometimes we want to allow user to pick a color from color picker. This post will bring you to two different type of color pickers.

YouTube video:


First one will appear like the following screen shot which is provided by google's android platform.


Code for create this type of dialog

ColorPicker.java
import android.os.Bundle;
import android.app.Dialog;
import android.content.Context;
import android.graphics.*;
import android.view.MotionEvent;
import android.view.View;

public class ColorPicker extends Dialog {

public interface OnColorChangedListener {
void colorChanged(int color);
}

private OnColorChangedListener mListener;
private int mInitialColor;

private static class ColorPickerView extends View {
private Paint mPaint;
private Paint mCenterPaint;
private final int[] mColors;
private OnColorChangedListener mListener;
        
ColorPickerView(Context c, OnColorChangedListener l, int color) {
super(c);
mListener = l;
mColors = new int[] {
0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00,
0xFFFFFF00, 0xFFFF0000
};
Shader s = new SweepGradient(0, 0, mColors, null);
            
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setShader(s);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(32);
            
mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterPaint.setColor(color);
mCenterPaint.setStrokeWidth(5);
}
        
private boolean mTrackingCenter;
private boolean mHighlightCenter;

@Override 
protected void onDraw(Canvas canvas) {
float r = CENTER_X - mPaint.getStrokeWidth()*0.5f;
            
canvas.translate(CENTER_X, CENTER_X);
            
canvas.drawOval(new RectF(-r, -r, r, r), mPaint);            
canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);
            
if (mTrackingCenter) {
int c = mCenterPaint.getColor();
mCenterPaint.setStyle(Paint.Style.STROKE);
                
if (mHighlightCenter) {
mCenterPaint.setAlpha(0xFF);
} else {
mCenterPaint.setAlpha(0x80);
}
canvas.drawCircle(0, 0, CENTER_RADIUS + mCenterPaint.getStrokeWidth(), mCenterPaint);
                
mCenterPaint.setStyle(Paint.Style.FILL);
mCenterPaint.setColor(c);
}
}
        
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(CENTER_X*2, CENTER_Y*2);
}
        
private static final int CENTER_X = 100;
private static final int CENTER_Y = 100;
private static final int CENTER_RADIUS = 32;

private int ave(int s, int d, float p) {
return s + java.lang.Math.round(p * (d - s));
}
        
private int interpColor(int colors[], float unit) {
if (unit <= 0) {
return colors[0];
}
if (unit >= 1) {
return colors[colors.length - 1];
}
            
float p = unit * (colors.length - 1);
int i = (int)p;
p -= i;
            
int c0 = colors[i];
int c1 = colors[i+1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
            
return Color.argb(a, r, g, b);
}
        
private static final float PI = 3.1415926f;

@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX() - CENTER_X;
float y = event.getY() - CENTER_Y;
boolean inCenter = java.lang.Math.sqrt(x*x + y*y) <= CENTER_RADIUS;
            
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTrackingCenter = inCenter;
if (inCenter) {
mHighlightCenter = true;
invalidate();
break;
}
case MotionEvent.ACTION_MOVE:
if (mTrackingCenter) {
if (mHighlightCenter != inCenter) {
mHighlightCenter = inCenter;
invalidate();
}
} else {
float angle = (float)java.lang.Math.atan2(y, x);                        
float unit = angle/(2*PI);
if (unit < 0) {
unit += 1;
}
mCenterPaint.setColor(interpColor(mColors, unit));
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (mTrackingCenter) {
if (inCenter) {
mListener.colorChanged(mCenterPaint.getColor());
}
mTrackingCenter = false;    
invalidate();
}
break;
}
return true;
}
}

public ColorPicker(Context context, OnColorChangedListener listener, int initialColor) {
super(context);
        
mListener = listener;
mInitialColor = initialColor;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnColorChangedListener l = new OnColorChangedListener() {
public void colorChanged(int color) {
mListener.colorChanged(color);
dismiss();
}
};

setContentView(new ColorPickerView(getContext(), l, mInitialColor));
setTitle("Pick a Color");
}
}
Following code will describe how to use this dialog

ColorPickerActivity.java
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

public class ColorPickerActivity extends Activity implements
  ColorPicker.OnColorChangedListener {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  this.activity = this;
 } 

 @Override
 public void colorChanged(int color) {  
  ColorPickerActivity.this.findViewById(android.R.id.content)
  .setBackgroundColor(color);
 }

 Activity activity;

 public void getColor(View v) {
  new ColorPicker(activity, ColorPickerActivity.this, Color.WHITE)
    .show();  
 }
}

Second one will appear like the following screen shot.



Code for create this type of dialog

ColorPicker.java
import android.app.Dialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class ColorPicker extends Dialog {

 public interface OnColorChangedListener {
  void colorChanged(String key, int color);
 }

 private OnColorChangedListener mListener;
 private int mInitialColor, mDefaultColor;
 private String mKey;

 private static class ColorPickerView extends View {
  private Paint mPaint;
  private float mCurrentHue = 0;
  private int mCurrentX = 0, mCurrentY = 0;
  private int mCurrentColor, mDefaultColor;
  private final int[] mHueBarColors = new int[258];
  private int[] mMainColors = new int[65536];
  private OnColorChangedListener mListener;

  ColorPickerView(Context c, OnColorChangedListener l, int color, int defaultColor) {
   super(c);
   mListener = l;
   mDefaultColor = defaultColor;

   // Get the current hue from the current color and update the main
   // color field
   float[] hsv = new float[3];
   Color.colorToHSV(color, hsv);
   mCurrentHue = hsv[0];
   updateMainColors();

   mCurrentColor = color;

   // Initialize the colors of the hue slider bar
   int index = 0;
   for (float i = 0; i < 256; i += 256 / 42) // Red (#f00) to pink
              // (#f0f)
   {
    mHueBarColors[index] = Color.rgb(255, 0, (int) i);
    index++;
   }
   for (float i = 0; i < 256; i += 256 / 42) // Pink (#f0f) to blue
              // (#00f)
   {
    mHueBarColors[index] = Color.rgb(255 - (int) i, 0, 255);
    index++;
   }
   for (float i = 0; i < 256; i += 256 / 42) // Blue (#00f) to light
              // blue (#0ff)
   {
    mHueBarColors[index] = Color.rgb(0, (int) i, 255);
    index++;
   }
   for (float i = 0; i < 256; i += 256 / 42) // Light blue (#0ff) to
              // green (#0f0)
   {
    mHueBarColors[index] = Color.rgb(0, 255, 255 - (int) i);
    index++;
   }
   for (float i = 0; i < 256; i += 256 / 42) // Green (#0f0) to yellow
              // (#ff0)
   {
    mHueBarColors[index] = Color.rgb((int) i, 255, 0);
    index++;
   }
   for (float i = 0; i < 256; i += 256 / 42) // Yellow (#ff0) to red
              // (#f00)
   {
    mHueBarColors[index] = Color.rgb(255, 255 - (int) i, 0);
    index++;
   }

   // Initializes the Paint that will draw the View
   mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
   mPaint.setTextAlign(Paint.Align.CENTER);
   mPaint.setTextSize(12);
  }

  // Get the current selected color from the hue bar
  private int getCurrentMainColor() {
   int translatedHue = 255 - (int) (mCurrentHue * 255 / 360);
   int index = 0;
   for (float i = 0; i < 256; i += 256 / 42) {
    if (index == translatedHue)
     return Color.rgb(255, 0, (int) i);
    index++;
   }
   for (float i = 0; i < 256; i += 256 / 42) {
    if (index == translatedHue)
     return Color.rgb(255 - (int) i, 0, 255);
    index++;
   }
   for (float i = 0; i < 256; i += 256 / 42) {
    if (index == translatedHue)
     return Color.rgb(0, (int) i, 255);
    index++;
   }
   for (float i = 0; i < 256; i += 256 / 42) {
    if (index == translatedHue)
     return Color.rgb(0, 255, 255 - (int) i);
    index++;
   }
   for (float i = 0; i < 256; i += 256 / 42) {
    if (index == translatedHue)
     return Color.rgb((int) i, 255, 0);
    index++;
   }
   for (float i = 0; i < 256; i += 256 / 42) {
    if (index == translatedHue)
     return Color.rgb(255, 255 - (int) i, 0);
    index++;
   }
   return Color.RED;
  }

  // Update the main field colors depending on the current selected hue
  private void updateMainColors() {
   int mainColor = getCurrentMainColor();
   int index = 0;
   int[] topColors = new int[256];
   for (int y = 0; y < 256; y++) {
    for (int x = 0; x < 256; x++) {
     if (y == 0) {
      mMainColors[index] = Color.rgb(
        255 - (255 - Color.red(mainColor)) * x / 255,
        255 - (255 - Color.green(mainColor)) * x / 255,
        255 - (255 - Color.blue(mainColor)) * x / 255);
      topColors[x] = mMainColors[index];
     } else
      mMainColors[index] = Color.rgb(
        (255 - y) * Color.red(topColors[x]) / 255,
        (255 - y) * Color.green(topColors[x]) / 255,
        (255 - y) * Color.blue(topColors[x]) / 255);
     index++;
    }
   }
  }

  @Override
  protected void onDraw(Canvas canvas) {
   int translatedHue = 255 - (int) (mCurrentHue * 255 / 360);
   // Display all the colors of the hue bar with lines
   for (int x = 0; x < 256; x++) {
    // If this is not the current selected hue, display the actual
    // color
    if (translatedHue != x) {
     mPaint.setColor(mHueBarColors[x]);
     mPaint.setStrokeWidth(1);
    } else // else display a slightly larger black line
    {
     mPaint.setColor(Color.BLACK);
     mPaint.setStrokeWidth(3);
    }
    canvas.drawLine(x + 10, 0, x + 10, 40, mPaint);
    // canvas.drawLine(0, x+10, 40, x+10, mPaint);
   }

   // Display the main field colors using LinearGradient
   for (int x = 0; x < 256; x++) {
    int[] colors = new int[2];
    colors[0] = mMainColors[x];
    colors[1] = Color.BLACK;
    Shader shader = new LinearGradient(0, 50, 0, 306, colors, null, Shader.TileMode.REPEAT);
    mPaint.setShader(shader);
    canvas.drawLine(x + 10, 50, x + 10, 306, mPaint);
   }
   mPaint.setShader(null);

   // Display the circle around the currently selected color in the
   // main field
   if (mCurrentX != 0 && mCurrentY != 0) {
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setColor(Color.BLACK);
    canvas.drawCircle(mCurrentX, mCurrentY, 10, mPaint);
   }

   // Draw a 'button' with the currently selected color
   mPaint.setStyle(Paint.Style.FILL);
   mPaint.setColor(mCurrentColor);
   canvas.drawRect(10, 316, 138, 356, mPaint);

   // Set the text color according to the brightness of the color
   if (Color.red(mCurrentColor) + Color.green(mCurrentColor) + Color.blue(mCurrentColor) < 384)
    mPaint.setColor(Color.WHITE);
   else
    mPaint.setColor(Color.BLACK);
   canvas.drawText("Pick", 74, 340, mPaint);

   // Draw a 'button' with the default color
   mPaint.setStyle(Paint.Style.FILL);
   mPaint.setColor(mDefaultColor);
   canvas.drawRect(138, 316, 266, 356, mPaint);

   // Set the text color according to the brightness of the color
   if (Color.red(mDefaultColor) + Color.green(mDefaultColor)
     + Color.blue(mDefaultColor) < 384)
    mPaint.setColor(Color.WHITE);
   else
    mPaint.setColor(Color.BLACK);
   canvas.drawText("Pick", 202, 340,
     mPaint);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
   setMeasuredDimension(276, 366);
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
   if (event.getAction() != MotionEvent.ACTION_DOWN)
    return true;
   float x = event.getX();
   float y = event.getY();

   // If the touch event is located in the hue bar
   if (x > 10 && x < 266 && y > 0 && y < 40) {
    // Update the main field colors
    mCurrentHue = (255 - x) * 360 / 255;
    updateMainColors();

    // Update the current selected color
    int transX = mCurrentX - 10;
    int transY = mCurrentY - 60;
    int index = 256 * (transY - 1) + transX;
    if (index > 0 && index < mMainColors.length)
     mCurrentColor = mMainColors[256 * (transY - 1) + transX];

    // Force the redraw of the dialog
    invalidate();
   }

   // If the touch event is located in the main field
   if (x > 10 && x < 266 && y > 50 && y < 306) {
    mCurrentX = (int) x;
    mCurrentY = (int) y;
    int transX = mCurrentX - 10;
    int transY = mCurrentY - 60;
    int index = 256 * (transY - 1) + transX;
    if (index > 0 && index < mMainColors.length) {
     // Update the current color
     mCurrentColor = mMainColors[index];
     // Force the redraw of the dialog
     invalidate();
    }
   }

   // If the touch event is located in the left button, notify the
   // listener with the current color
   if (x > 10 && x < 138 && y > 316 && y < 356)
    mListener.colorChanged("", mCurrentColor);

   // If the touch event is located in the right button, notify the
   // listener with the default color
   if (x > 138 && x < 266 && y > 316 && y < 356)
    mListener.colorChanged("", mDefaultColor);

   return true;
  }
 }

 public ColorPicker(Context context, OnColorChangedListener listener,
   String key, int initialColor, int defaultColor) {
  super(context);

  mListener = listener;
  mKey = key;
  mInitialColor = initialColor;
  mDefaultColor = defaultColor;
 }

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  OnColorChangedListener l = new OnColorChangedListener() {
   public void colorChanged(String key, int color) {
    mListener.colorChanged(mKey, color);
    dismiss();
   }
  };

  setContentView(new ColorPickerView(getContext(), l, mInitialColor,
    mDefaultColor));
  setTitle("Pick a color");

 }
}
Following code will describe how to use this dialog

ColorPickerActivity.java
package com.example.colorpicker;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

public class ColorPickerActivity extends Activity implements
  ColorPicker.OnColorChangedListener {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  this.activity = this;
 } 

 @Override
 public void colorChanged(String str,int color) {  
  ColorPickerActivity.this.findViewById(android.R.id.content)
  .setBackgroundColor(color);
 }

 Activity activity;

 public void getColor(View v) {
  new ColorPicker(activity, this, "", Color.BLACK, Color.WHITE).show(); 
 }
}
xml code for both activity

main.xml
&ltRelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".ColorPickerActivity" &gt

    &ltButton
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:onClick="getColor"
        android:text="Button" /&gt

&lt/RelativeLayout&gt
Sample output screen shot for both dialogs.



I hope this post is useful to you. kindly share your feedback as comment here.



Source code on GitHub



Thank You