Search This Blog

Showing posts with label Android Dialog. Show all posts
Showing posts with label Android Dialog. Show all posts

Saturday, 20 October 2012

Creating DatePicker using DialogFragment in android

Android has transform its UI after 3.1. They had deprecated Activity Group and so many other thing and introduce Fragment. Maintaining Fragment is comparatively easy. Just few month back they they introduce DialogFragment and deprecated showDialog(id) method. it affects creating DatePicker and TimePicker also.so today we will discuss about creating DatePicker using brand new concept DialogFragment.

For More Information on  Fragment Visit Integration Of Action Bar And Fragment

Creating DatePicker using DialogFragment is quite easy. Lets divide it in step and make it more easy :)

Step 1) Repeated step create a new Project

Step 2) Add one button to your main xml. So that on click this button we can show Date Picker

<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" >

    <Button
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50dp"
        android:text="@string/show_date_picker_fragment" />

</LinearLayout>  
View Of XML

Step 3) Change your activity to a Fragment Activity and replace with below code

package com.home;

import java.util.Calendar;

import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.Toast;

import com.dialog.DatePickerFragment;

public class MainActivity extends FragmentActivity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  findViewById(R.id.date).setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    showDatePicker();
   }
  });
 }

 private void showDatePicker() {
  DatePickerFragment date = new DatePickerFragment();
  /**
   * Set Up Current Date Into dialog
   */
  Calendar calender = Calendar.getInstance();
  Bundle args = new Bundle();
  args.putInt("year", calender.get(Calendar.YEAR));
  args.putInt("month", calender.get(Calendar.MONTH));
  args.putInt("day", calender.get(Calendar.DAY_OF_MONTH));
  date.setArguments(args);
  /**
   * Set Call back to capture selected date
   */
  date.setCallBack(ondate);
  date.show(getSupportFragmentManager(), "Date Picker");
 }

 OnDateSetListener ondate = new OnDateSetListener() {
  @Override
  public void onDateSet(DatePicker view, int year, int monthOfYear,
    int dayOfMonth) {
   Toast.makeText(
     MainActivity.this,
     String.valueOf(year) + "-" + String.valueOf(monthOfYear)
       + "-" + String.valueOf(dayOfMonth),
     Toast.LENGTH_LONG).show();
  }
 };

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

Step Final ) Now you are done from your side..We just need to create one class that will extends DialogFragment and will return a DatePicker .

package com.dialog;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

public class DatePickerFragment extends DialogFragment {
 OnDateSetListener ondateSet;

 public DatePickerFragment() {
 }

 public void setCallBack(OnDateSetListener ondate) {
  ondateSet = ondate;
 }

 private int year, month, day;

 @Override
 public void setArguments(Bundle args) {
  super.setArguments(args);
  year = args.getInt("year");
  month = args.getInt("month");
  day = args.getInt("day");
 }

 @Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
  return new DatePickerDialog(getActivity(), ondateSet, year, month, day);
 }
}  

See how to integrate Action bar with Tab

Wednesday, 1 August 2012

Date Time Picker in android

We know how simple is to create Date Picker Dialog and  Time Picker Dialog ! but so what about a situation where we  need to pick Time and Date both at once with all attributes e.g AM_PM, second, minute, Hour, Month, Year etc. We got stuck  right?

I have search a lot about this on Google but i did not find efficient and easy solution. So decide to write about this important concept. While you are developing any android application then you just copy one class from my sample project. and your work has done.

There are two simple step to understand what's going on in my project

1) Create object of CustomDateTimePicker with two argument Your Current activity context and one Call back listener so that when you select time and date, it will return result

2) CustomDateTimePicker has number of method to fulfill your custom requirement like---


/**
* Pass Directly current time format it will return AM and PM if you set
* false
*/
custom.set24HourFormat(false);

                 /**
* Pass Directly current data and time to show when it pop up
*/
custom.setDate(Calendar.getInstance());

Custom is instance of my CustomDateTimePicker .Except this , CustomDateTimePicker  has number of method. 


                       The Output of my sample project will be like these screen shot.

Date time Picker
Date And Time Picker

Selected Value
          
                                                       

                                                              Download Source Code


Time Picker in android

In my previous post Date Picker in android, I discuss about how to create Date Picker now we will cover another important aspect Timepickerdialog in android. While developing android application we meet so many situation where we need to pick time. In time picker also, we have two important  steps to remember

1) Call back listener that will return Time in hour and minute 

2) And Time picker dialog object


Note - Always use overridden method onCreateDialog(int id) of activity to avoid window leak exception while changing orientation of activity

Date picker in android

In android application development, picker and dialog has an important place. Today i am going to discuss how to create a simple date picker dialog and time picker dialog. All though i know i am very late to write about this basic concept, but i realize that even-though a lots of matter and article available on this but they lack in term of explanation. So here i go with my attempt.

We need two things here

1) Dialog picker (either date or time) Object

2) And call back so that we can capture date or time when user set date


We will set current date or time when picker will open first time using calender object. Creating Datepickerdialog object inside overridden method of activity ,oncreatedialog() is best way. It will handle the orientation change effectively and you will avoid window leak exception quite easily

Monday, 23 July 2012

Replacing spinner with drop down alert in android application

Dialog box are powerful tools in android. They have given so much access in dialog box so that we  do not need to use spinner. You can create simple Alert Dialog, Custom Alert dialog, Multiple choice, Single choice , Alert Dialog with Base adapter. We easily can create them.

I am going to create All type of dialog boxes with screen shot and source code.

1) Simple Alert Box or Default Alert Box - creating a simple alert dialog is very simple

   private void SimpleAlert() {  
     Builder builder = new AlertDialog.Builder(this);  
     builder.setTitle("Simple Alert");  
     builder.setMessage("This is simple alert box");  
     builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {  
       @Override  
       public void onClick(DialogInterface dialog, int which) {  
         dialog.dismiss();  
       }  
     });  
     AlertDialog alert = builder.create();  
     alert.show();  
   }  


Wednesday, 4 April 2012

Android: Creating custom alert dialog

In android sometimes we want to display some data but we do not want to start a new activity.As starting a new activity is not feasible in some cases.So what should we do?

First take a case

We have news showing in List-View now if some one click on on particular news then it should show detail about this this news.so instead of starting new activity we can just pop a custom dialog (with same view as activity) then we will use a custom dialog for this. Because of its benefit we call this custom dialog as Dialog activity

Step 1) Create a new project in android

Step 2) Change your main.xml as follows

  <?xml version="1.0" encoding="utf-8" ?>  
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">  
     <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start" android:id="@+id/show_dialog" />  
  </LinearLayout>  


Tuesday, 21 February 2012

Custom Color picker dialog in android

Here i wrote a code with help of AndroidDeveloper'sBestGuide. It is just concept of implement canvas with a dialog box.
We create different color by using Canvas. and then we select different color with the help of canvas.
With the help of this example ,you will also read how to create a custom diaolog

For more information about canvas you. Game Development using Surface View Part III , Game Development Using Canvas Part I

Lets do it step by step


1) Create One XML file in res/layout/main.xml


<?xml version="1.0" encoding="UTF-8"?>  
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="wrap_content"  
   android:padding="20dip" android:id="@+id/main"  
   android:orientation="vertical">  
   <Button android:layout_width="wrap_content"     android:layout_height="wrap_content"  
     android:layout_gravity="center" android:text="Change Background"  
     android:id="@+id/change_color"/>  
 </LinearLayout>  

2) Create One activity and register in manifest file  

Never forget to register your activity into manifest. This activity has only one button. If you click button then it will pop up color picker. Then you can select any color by just touching it


public class ColorPicker extends Activity{  
   private LinearLayout ll;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.main);  
     Button btn=(Button) findViewById(R.id.change_color);  
     ll=(LinearLayout) findViewById(R.id.main);  
     btn.setOnClickListener(new OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         ColorPickerDialog cpd=new ColorPickerDialog(ColorPicker.this, listener, 0);  
         cpd.show();  
       }  
     });  
    }  
    @Override  
   protected void onResume() {  
     super.onResume();  
     ll.setBackgroundColor(ColorAh);  
   }  
   OnColorChangedListener listener=new OnColorChangedListener() {  
       @Override  
       public void colorChanged(int color) {  
         Toast.makeText(ColorPicker.this, ""+color, Toast.LENGTH_LONG).show();  
         ColorAh=color;  
         ll.setBackgroundColor(ColorAh);  
       }  
     };  
   private int ColorAh=Color.BLACK;  
 }  

3)Now create a custom dialog

This is the main task. Here with the help of a canvas we will create surface with different color. If you touch any coordinate then it will give respective point color code. This all is a part of a custom dialog. When user touch any point we will select a color and dismiss dialog box.


public class ColorPickerDialog 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 floatToByte(float x) {  
       int n = java.lang.Math.round(x);  
       return n;  
     }  
     private int pinToByte(int n) {  
       if (n < 0) {  
         n = 0;  
       } else if (n > 255) {  
         n = 255;  
       }  
       return n;  
     }  
     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;  
       // now p is just the fractional part [0...1) and i is the index  
       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 int rotateColor(int color, float rad) {  
       float deg = rad * 180 / 3.1415927f;  
       int r = Color.red(color);  
       int g = Color.green(color);  
       int b = Color.blue(color);  
       ColorMatrix cm = new ColorMatrix();  
       ColorMatrix tmp = new ColorMatrix();  
       cm.setRGB2YUV();  
       tmp.setRotate(0, deg);  
       cm.postConcat(tmp);  
       tmp.setYUV2RGB();  
       cm.postConcat(tmp);  
       final float[] a = cm.getArray();  
       int ir = floatToByte(a[0] * r + a[1] * g + a[2] * b);  
       int ig = floatToByte(a[5] * r + a[6] * g + a[7] * b);  
       int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b);  
       return Color.argb(Color.alpha(color), pinToByte(ir),  
                pinToByte(ig), pinToByte(ib));  
     }  
     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);  
             // need to turn angle [-PI ... PI] into unit [0....1]  
             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;  // so we draw w/o halo  
             invalidate();  
           }  
           break;  
       }  
       return true;  
     }  
   }  
   public ColorPickerDialog(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");  
   }  
 }  

 Now screen shot will show our hard work into output :). See the screen shot. And Let me if you face any problem while implementing it.
                                               
Main Screen
      Click on button ? it immediately will pop up all your hard work in term of dialog


Android trainner color picker in android
Now Select color

After Selecting Color

Android News and source code