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

Monday 3 November 2014

Android Tutorial 44 : Timepicker and DatePicker Dialog in Android

We can use Time Picker  and Date Picker   widget to select a time and date , but TimePickerDialog and DatePickerDialog  is a better choice to do that.

In this post I will discuss how to use DatePickerDialog and TimePickerDialog to select Date and Time.



DatePickerDialog In Android
                       





Here I have described briefly, the Example with full source code is given below after this.
  
Declare following Variables in your Activity/Class

static final int DATE_DIALOG_ID = 0;
static final int TIME_DIALOG_ID=1;

public  int year,month,day,hour,minute;  // declare  the variables to show the date and time whenTime and                                                          //Date Picker Dialog first appears

private int mYear, mMonth, mDay,mHour,mMinute; // variables to save user selected date and time

In the constructor you can initiallise the variable to current date and time.

                   year=month=day=hour=minute=1;
                    final Calendar c = Calendar.getInstance();
                    mYear = c.get(Calendar.YEAR);
                    mMonth = c.get(Calendar.MONTH);
                    mDay = c.get(Calendar.DAY_OF_MONTH);
                    mHour = c.get(Calendar.HOUR_OF_DAY);
                    mMinute = c.get(Calendar.MINUTE);



//call the method when you need to show DatePickerDialog
 showDialog(DATE_DIALOG_ID);
//call the method when you need to show DatePickerDialog
  showDialog(TIME_DIALOG_ID);

// Register  DatePickerDialog listener
 private DatePickerDialog.OnDateSetListener mDateSetListener =
                        new DatePickerDialog.OnDateSetListener() {
                 // the callback received when the user "sets" the Date in the DatePickerDialog
                            public void onDateSet(DatePicker view, int yearSelected,
                                                  int monthOfYear, int dayOfMonth) {
                               year = yearSelected;
                               month = monthOfYear;
                               day = dayOfMonth;
                              Toast.makeText(getApplicationContext(), "Date selected is:"+day+"-"+month+"-"+year, Toast.LENGTH_LONG).show();
                                                         }
                        };


   // Register  TimePickerDialog listener                 
                        private TimePickerDialog.OnTimeSetListener mTimeSetListener =
                            new TimePickerDialog.OnTimeSetListener() {
             // the callback received when the user "sets" the TimePickerDialog in the dialog
                                public void onTimeSet(TimePicker view, int hourOfDay, int min) {

                                    hour = hourOfDay;
                                    minute = min;
                                   Toast.makeText(getApplicationContext(), "Time selected is:"+hour+"-"+minute, Toast.LENGTH_LONG).show();
                                                                  }
                            };


// Method automatically gets Called when you call showDialog()  method
                        @Override
                        protected Dialog onCreateDialog(int id) {
                            switch (id) {
                            case DATE_DIALOG_ID:
                                return new DatePickerDialog(this,
                                            mDateSetListener,
                                            mYear, mMonth, mDay);
                            case TIME_DIALOG_ID:
                                return new TimePickerDialog(this,
                                        mTimeSetListener, mHour, mMinute, false);
                            
                            }
                            return null;
                        }
                        

Date And Time Picker Dialog Example with Full Source Code

In the example   I have 2 buttons  
1: Select Date - to show DatePickerDialog 
2: Select Time - to show TimePickertDialog
When user selects a Date and Time in respective Dialogs we will set the selected date and time in Respective buttons. We will set selected date in Select Date Button and selected time in Select Time Button(See the last Snapshot)


main.xml



DatePickerDialog In Android



<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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:textSize="25dp"
        android:layout_gravity="center_horizontal"
        android:text="Date And Time Picker Example" />

    <Button
        android:id="@+id/buttonSelectDate"
        android:layout_marginTop="20dp"
        android:textSize="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Select Date" />

    <Button
        android:id="@+id/buttonSelectTime"
        android:layout_marginTop="20dp"
        android:textSize="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Select Time" />

</LinearLayout>




DateAndTimePickerActivity.java 

public class DateAndTimePickerActivity extends Activity
{

            Button btnSelectDate,btnSelectTime;
           
            static final int DATE_DIALOG_ID = 0;
            static final int TIME_DIALOG_ID=1;
           
            // declare  the variables to Show/Set the date and time whenTime and  Date Picker Dialog first appears
            public  int year,month,day,hour,minute; 
            // variables to save user selected date and time
            private int mYear, mMonth, mDay,mHour,mMinute;
           
            // constructor
           
            public DateAndTimePickerActivity()
            {
                        // Assign current Date and Time Values to Variables
                        final Calendar c = Calendar.getInstance();
                        mYear = c.get(Calendar.YEAR);
                        mMonth = c.get(Calendar.MONTH);
                        mDay = c.get(Calendar.DAY_OF_MONTH);
                        mHour = c.get(Calendar.HOUR_OF_DAY);
                        mMinute = c.get(Calendar.MINUTE);
            }
           
            @Override
            protected void onCreate(Bundle savedInstanceState)
            {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.date_and_time_picker);
                       
                        // get the references of buttons
                        btnSelectDate=(Button)findViewById(R.id.buttonSelectDate);
                        btnSelectTime=(Button)findViewById(R.id.buttonSelectTime);
                       
                        // Set ClickListener on btnSelectDate 
                        btnSelectDate.setOnClickListener(new View.OnClickListener() {
                           
                            public void onClick(View v) {
                                // Show the DatePickerDialog
                                 showDialog(DATE_DIALOG_ID);
                            }
                        });
                       
                        // Set ClickListener on btnSelectTime
                        btnSelectTime.setOnClickListener(new View.OnClickListener() {
                           
                            public void onClick(View v) {
                                // Show the TimePickerDialog
                                 showDialog(TIME_DIALOG_ID);
                            }
                        });
                       
            }
           
            
            // Register  DatePickerDialog listener

             private DatePickerDialog.OnDateSetListener mDateSetListener =
                                    new DatePickerDialog.OnDateSetListener() {
                                // the callback received when the user "sets" the Date in the DatePickerDialog
                                        public void onDateSet(DatePicker view, int yearSelected,
                                                              int monthOfYear, int dayOfMonth) {
                                           year = yearSelected;
                                           month = monthOfYear;
                                           day = dayOfMonth;
                                           // Set the Selected Date in Select date Button
                                           btnSelectDate.setText("Date selected : "+day+"-"+month+"-"+year);
                                        }
                                    };

               // Register  TimePickerDialog listener                
                                    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
                                        new TimePickerDialog.OnTimeSetListener() {
                                 // the callback received when the user "sets" the TimePickerDialog in the dialog
                                            public void onTimeSet(TimePicker view, int hourOfDay, int min) {
                                                hour = hourOfDay;
                                                minute = min;
                                                // Set the Selected Date in Select date Button
                                                btnSelectTime.setText("Time selected :"+hour+"-"+minute);
                                              }
                                        };


            // Method automatically gets Called when you call showDialog()  method
                                    @Override
                                    protected Dialog onCreateDialog(int id) {
                                        switch (id) {
                                        case DATE_DIALOG_ID:
                                 // create a new DatePickerDialog with values you want to show 
                                            return new DatePickerDialog(this,
                                                        mDateSetListener,
                                                        mYear, mMonth, mDay);
                                // create a new TimePickerDialog with values you want to show
                                        case TIME_DIALOG_ID:
                                            return new TimePickerDialog(this,
                                                    mTimeSetListener, mHour, mMinute, false);
                                      
                                        }
                                        return null;
                                    }
                                    

}


TimePickerDialog In Android

Sunday 2 November 2014

Android Tutorial 19 : Adding Check Boxes In Alert Dialog

We can also add check boxes in Alert Dialog and we can check multiple, it is used when we want mutiple option to be selected.

Handling the Click Events on CheckBoxes:

when a Checkbox is clocked means it is checked or unchecked obClick() method is called and the index of the selected item is passed, we can use this index to get the item which is checked




Create an Object of AlertDialog

AlertDialog dialog; 

//following code will be in your activity.java file 

final CharSequence[] items = {" Easy "," Medium "," Hard "," Very Hard "};
                // arraylist to keep the selected items
                final ArrayList seletedItems=new ArrayList();
              
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Select The Difficulty Level");
                builder.setMultiChoiceItems(items, null,
                        new DialogInterface.OnMultiChoiceClickListener() {

                 // indexSelected contains the index of item (of which checkbox checked)
                 @Override
                 public void onClick(DialogInterface dialog, int indexSelected,
                         boolean isChecked) {
                     if (isChecked) {
                         // If the user checked the item, add it to the selected items

                         // write your code when user checked the checkbox 
                         seletedItems.add(indexSelected);
                     } else if (seletedItems.contains(indexSelected)) {
                         // Else, if the item is already in the array, remove it 

                         // write your code when user Uchecked the checkbox 
                         seletedItems.remove(Integer.valueOf(indexSelected));
                     }
                 }
             })
              // Set the action buttons
             .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int id) {
                     //  Your code when user clicked on OK
                     //  You can write the code  to save the selected item here

                   
                 }
             })
             .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int id) {
                    //  Your code when user clicked on Cancel
                  
                 }
             });
      
                dialog = builder.create();//
AlertDialog dialog; create like this outside onClick
                dialog.show();
        }

Android Tutorial 17 : Android Alert Dialog Example

What are  Alert Dialogs

An Alert Dialog is used to show some information or to prompts the user to make.
Dialogs can also be used to take input from users, such dialogs are called Customized Dialogs

Buiding  Alert Dialogs:    

 AlertDialog class is used to create Alert Dialog.

Three things are required to create a dialog.
1:Title : The title of the dialog
2: Message: The message to be given in dialog.
3: Image(Optional): Image to displayed in Title Bar


We can also add buttons in Alert Dialog.

Code to create Alert Dialog

AlertDialog dialog;
                dialog = new AlertDialog.Builder(this).create();
                dialog.setTitle("Close");
                dialog.setIcon(android.R.drawable.ic_dialog_info);
                dialog.setMessage("Want to close this App").


dialog.show();


Adding Buttons to Dialog:


dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Yes",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which)
            {
                   
                // Your Code
            }   
        });
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "No",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which)
            {
                   
                  // Your Code
            }   
        });
        dialog.show();


Dismissing A dialog 


dialog.dismiss();