Wednesday, February 25, 2015

Android DatePicker sample code

Following are the code for date picker from edittext in fragment class.
1.Put the datepicker onclick method inside oncreate method.
2.Call the datepicker class and assign the selected value to the field in updatelabel method.
3.It is simple to implement and get the selected date

// Importing EditText
pDateofBirth = (EditText) rootView.findViewById(R.id.dp_pi_dob);

// datepicker onclick method
  pDateofBirth.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    new DatePickerDialog(getActivity(), date, myCalendar
      .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
      myCalendar.get(Calendar.DAY_OF_MONTH)).show();

   }
  });

/* DatePicker event start */
 Calendar myCalendar = Calendar.getInstance();

 DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
  @Override
  public void onDateSet(DatePicker view, int year, int monthOfYear,
    int dayOfMonth) {
   // TODO Auto-generated method stub
   myCalendar.set(Calendar.YEAR, year);
   myCalendar.set(Calendar.MONTH, monthOfYear);
   myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
   updateLabel();
  }
 };

 private void updateLabel() {
  String myFormat = "MM/dd/yyyy"; // In which you need put here
  SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

  pDateofBirth.setText(sdf.format(myCalendar.getTime()));
 }

XML File

<EditText
                            android:id="@+id/dp_pi_dob"
                            style="@style/CT_com_containerNormalEditView"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight=".95"
                            android:inputType="date"
                            android:onClick="selectDate"
                            android:focusable="false"
                            bootstrapbutton:be_roundedCorners="true" />

No comments:

Post a Comment