Pregunta

I am beginner to Android and trying to implement a date picker dialog in Android.

For that purpose I am studying this link: Date Picker - Developers Android.

So far I have understood but my requirement is when I click a button I need to get the date picker dialog and when I set the date picker I need to set the value in a Edit Text.

According to the link we need to extend DialogFragment and implement DatePickerDialog.OnDateSetListener.

Now my understanding to follow below process to achieve this:

  1. Create a new XML with only date picker.
  2. Create a Java file and implement the date picker code.
  3. In parent class button click call the Intent to the datepicker class
  4. Pass the value to the parent class Edit Text

Is this the correct approach?

¿Fue útil?

Solución

Here is the complete code for that..

Button bt_setdate=(Button) findViewById(R.id.bt_setdate);
bt_setdate.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            showDialog(DATE_DIALOG_ID);
            // get the current date

        }
    });

and outside onCreate()

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        // set date picker as current date
          //Edit------------------------------------------//
            final Calendar c = Calendar.getInstance();
        Year  = c.get(Calendar.YEAR);
        Month = c.get(Calendar.MONTH);
        day   = c.get(Calendar.DAY_OF_MONTH);
       //Edit------------------------------------------//
        return new DatePickerDialog(this, datePickerListener, 
                year, month,day);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
        year = selectedYear;
        month = selectedMonth;
        day = selectedDay;
        String selmonth=cm.getMonth(month);

        bookingdate=String.valueOf(year)+"-"+String.valueOf(month)+"-"+String.valueOf(day);

    }
};

bookingdate contains the date that is selected.. and add this to your layout

<DatePicker
    android:id="@+id/dpResult"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:visibility="gone"/>

Otros consejos

try below code:-

DatePickerDialog.OnDateSetListener                date;
Calendar                                          myCalendar;
dob_add_emp             = (TextView) findViewById(R.id.dob_add_emp);

myCalendar = Calendar.getInstance();

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();
    }

};

dob_add_emp.setOnClickListener(new OnClickListener()
{   
    @Override
    public void onClick(View v)
    {
        // TODO Auto-generated method stub
        if (dob_add_emp.getText().toString().equals(""))
        {
            new DatePickerDialog(AddEmployee.this, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar
                    .get(Calendar.DAY_OF_MONTH)).show();
        }
        else
        {
            String dob = dob_add_emp.getText().toString();
            String[] d = dob.split("-");

            new DatePickerDialog(AddEmployee.this, date, Integer.parseInt(d[0]), Integer.parseInt(d[1]) - 1, Integer.parseInt(d[2]))
                    .show();
        }
    }
});



@SuppressLint("SimpleDateFormat")

private void updateLabel()
{
    try


{
    // String myFormat = "MM/dd/yyyy"; // In which you need put here
    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    Date current_date = new Date();
    Date session_date = sdf.parse(sdf.format(myCalendar.getTime()));
    int difference = current_date.compareTo(session_date);
    if (difference == 0)
    {
        dob_add_emp.setText(sdf.format(myCalendar.getTime()));
    }
    else if (difference < 0)
    {
        Toast.makeText(getBaseContext(), "Select date before current date", Toast.LENGTH_LONG).show();
    }
    else
    {
        dob_add_emp.setText(sdf.format(myCalendar.getTime()));
    }
}
catch (Exception e)
{
    // TODO: handle exception
    e.printStackTrace();
}
}

Hi plz use the code on click of button where you wanna open date picker dialog

 static final int DATE_DIALOG_ID = 999;
 private int year;
 private int month;
 private int day;

final Calendar c = Calendar.getInstance();

year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);

btnDate.setOnClickListener(new OnClickListener() {

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

add following methods to your activity as

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
    // set date picker as current date
    return new DatePickerDialog(this, datePickerListener, year, month,
            day);
}
return null;
}

public DatePickerDialog.OnDateSetListener datePickerListener =
                  new    DatePickerDialog.   OnDateSetListener(){

       // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
        int selectedMonth, int selectedDay) {
         year = selectedYear;
         month = selectedMonth;
         day = selectedDay;

         // set selected date into edittext
           txtDate.setText(new StringBuilder().append(month + 1).append("-")
            .append(day).append("-").append(year).append(" "));

        }
     };

you can format date as your reuirement..

package com.androidexample.datepicker;

import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class DatePickerExample extends Activity {

    private TextView Output;
    private Button changeDate;

    private int year;
    private int month;
    private int day;

    static final int DATE_PICKER_ID = 1111; 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Output = (TextView) findViewById(R.id.Output);
        changeDate = (Button) findViewById(R.id.changeDate);

        // Get current date by calender

        final Calendar c = Calendar.getInstance();
        year  = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day   = c.get(Calendar.DAY_OF_MONTH);

        // Show current date

        Output.setText(new StringBuilder()
                // Month is 0 based, just add 1
                .append(month + 1).append("-").append(day).append("-")
                .append(year).append(" "));

        // Button listener to show date picker dialog

        changeDate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                // On button click show datepicker dialog 
                showDialog(DATE_PICKER_ID);

            }

        });
   }


    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_PICKER_ID:

            // open datepicker dialog. 
            // set date picker for current date 
            // add pickerListener listner to date picker
            return new DatePickerDialog(this, pickerListener, year, month,day);
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        @Override
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {

            year  = selectedYear;
            month = selectedMonth;
            day   = selectedDay;

            // Show selected date 
            Output.setText(new StringBuilder().append(month + 1)
                    .append("-").append(day).append("-").append(year)
                    .append(" "));

           }
        };

}

main.xml

<?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:id="@+id/changeDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click To Change Date" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Current/Selected Date (M-D-YYYY): "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/Output"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />



</LinearLayout>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top