dcsimg
October 1, 2016
Hot Topics:

Using the Basic UI Controls in Android: Buttons, Texts, Checkboxes, Radio Buttons, Toggle Buttons, and Spinners (Building a Simple Android Application Demo)

  • January 27, 2016
  • By Vipul Patel
  • Send Email »
  • More Articles »

Introduction

To help provide a great user experience, Android provides ready-made dialogs to choose date or time. These dialogs are called pickers and allow users to choose each part of the date, hiding away the complexities associates with time zone and user locale.

Picker Basics

The time picker allows the user to choose the hour, minute, and whether it is AM or PM. The date picker allows the user to choose day, month, and year.

To help with lifecycle management, it is recommended to use DialogFragment class to host the picker controls.

To use pickers with DialogFragment, we need to:

  1. Define a fragment class that inherits from DialogFragment and returns a TimePickerDialog or DatePickerDialog on the onCreateDialog method call of the fragment.
  2. Implement the TimePickerDialog.OnTimeSetListener/DatePickerDialog.OnDateSetListener interface that is triggered when the user sets the time.

Let us create a simple Android application that demonstrates this.

Hands On

Fire up Android Studio and start a new Android Studio project.

Picker1
Figure 1: Starting a new Android Studio project

Provide PickerControlsDemo as the Application Name and click Next.

Picker2
Figure 2: Naming the application

On the next screen, leave the default values and click Next.

Picker3
Figure 3: Leaving the default values in place

On the "Add an activity to Mobile" page, choose "Blank Activity". This creates an application with a single activity.

Picker4
Figure 4: Adding a Blank Activity

We then are prompted to customize the activity. We will leave the default values unchanged.

Picker5
Figure 5: Again, leaving the default values in place

Click Finish to create the project files.

Right-click the Java node in the project explorer and select New -> Java class. Enter TimePicker and click OK,

Picker6
Figure 6: Entering "TimePickerFrag"

The default implementation is shown below:

package com.example.vipul.pickercontrolsdemo;
/**
 * Created by vipul on 11/30/2015.
 */
public class TimePickerFrag  {
}

We will now update this, as follows.

public class TimePickerFrag extends DialogFragment
   implements TimePickerDialog.OnTimeSetListener {

Next, we implement the onCreateDialog method and onTimeSet methods.

//timepickerfrag.java
package com.example.vipul.pickercontrolsdemo;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;

import java.util.Calendar;

/**
 * Created by vipul on 11/30/2015.
 */
public class TimePickerFrag extends DialogFragment
      implements TimePickerDialog.OnTimeSetListener {

   @NonNull
   @Override
   public Dialog onCreateDialog(Bundle savedInstanceState) {
      final Calendar calendar = Calendar.getInstance();
      int hh = calendar.get(Calendar.HOUR_OF_DAY);
      int mm = calendar.get(Calendar.MINUTE);


      return new TimePickerDialog(getActivity(), this, hh, mm,
      DateFormat.is24HourFormat(getActivity()));

   }

   @Override
   public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
      // do something
   }
}

Similarly, we implement the DialogFragment for Date Picker. Add another Java class, called DatePickerFrag, to the project.

//DatepickerFrag.java
package com.example.vipul.pickercontrolsdemo;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import java.util.Calendar;

/**
 * Created by vipul on 11/30/2015.
 */
public class DatePickerFrag extends DialogFragment
      implements DatePickerDialog.OnDateSetListener {

   @NonNull
   @Override
   public Dialog onCreateDialog(Bundle savedInstanceState) {

      final Calendar calendar = Calendar.getInstance();
      int yy = calendar.get(Calendar.YEAR);
      int mm = calendar.get(Calendar.MONTH);
      int dd = calendar.get(Calendar.DAY_OF_MONTH);

      return new DatePickerDialog(getActivity(),
         this, yy, mm, dd);


   }

   @Override
   public void onDateSet(DatePicker view, int year,
      int monthOfYear, int dayOfMonth) {
   }
}

Lastly, we add two buttons to MainActivity.xml and wire up the click events to instantiate the dialogs.

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

   <TextView android:text="@string/hello_world"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textView" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Time Picker"
      android:id="@+id/buttonTimePicker"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="70dp"
      android:onClick="onButtonTimePickerClick" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Date Picker"
      android:id="@+id/buttonDatePicker"
      android:layout_centerVertical="true"
      android:layout_alignRight="@+id/buttonTimePicker"
      android:layout_alignEnd="@+id/buttonTimePicker" />

</RelativeLayout>

In MainActivity.java, we implement the click event handlers.

public void onButtonTimePickerClick(View view){
   android.support.v4.app.DialogFragment timepickerFrag =
      new TimePickerFrag();
   timepickerFrag.show(getSupportFragmentManager(),
      "mytimepicker");
}


public void onButtonDatePickerClick(View view){
   android.support.v4.app.DialogFragment datepickerFrag =
      new DatePickerFrag();
   datepickerFrag.show(getSupportFragmentManager(),
      "mydatepicker");
}

Our application is now complete. When we launch the application and click the buttons, we can see the pickers in action.

Picker7
Figure 7: Time Picker

Picker8
Figure 8: Date picker

Summary

In this article, we learned how to work with the Android picker control. I hope you have found this information useful. You can download the sample code from here.

About the Author

Vipul Patel is a technology geek based in Seattle. He can be reached at vipul.patel@hotmail.com. You can visit his LinkedIn profile at https://www.linkedin.com/pub/vipul-patel/6/675/508.


Tags: Java, Android, android studio, Android Picker Control




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel