web-dev-qa-db-fra.com

Datepicker: Comment faire apparaître le datepicker quand vous cliquez sur edittext

Je veux afficher la fenêtre contextuelle de datepicker. J'ai trouvé des exemples mais je ne les comprends pas correctement. J'ai un edittext et je veux que lorsque je clique sur edittext, la boîte de dialogue datepicker doit apparaître et après avoir réglé la date, la date doit apparaître dans edittext au format jj/mm/aaaa. Veuillez me fournir un exemple de code ou de bons liens.

214
Surabhi Pandey

Essayez ceci dans le fichier XML:

<EditText
   Android:id="@+id/Birthday"
   custom:font="@string/font_avenir_book"
   Android:clickable="true"
   Android:editable="false"
   Android:hint="@string/birthday"/>

Maintenant en fichier Java:

final Calendar myCalendar = Calendar.getInstance();

EditText edittext= (EditText) findViewById(R.id.Birthday);
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();
    }

};

edittext.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        new DatePickerDialog(classname.this, date, myCalendar
                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                myCalendar.get(Calendar.DAY_OF_MONTH)).show();
    }
});

Ajoutez maintenant la méthode dans l'activité ci-dessus.

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

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

Ajoutez Android:focusable="false" dans le fichier XML de EditText pour permettre une simple pression.

560
Android_coder

Je ne parviens pas à faire travailler ces personnes, alors j'ajouterai le mien au cas où cela aiderait.

public class MyEditTextDatePicker  implements OnClickListener, OnDateSetListener {   
EditText _editText;
private int _day;
private int _month;
private int _birthYear;
private Context _context;

public MyEditTextDatePicker(Context context, int editTextViewID)
{       
    Activity act = (Activity)context;
    this._editText = (EditText)act.findViewById(editTextViewID);
    this._editText.setOnClickListener(this);
    this._context = context;
}

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    _birthYear = year;
    _month = monthOfYear;
    _day = dayOfMonth;
    updateDisplay();
}
@Override
public void onClick(View v) {
    Calendar calendar = Calendar.getInstance(TimeZone.getDefault());

    DatePickerDialog dialog = new DatePickerDialog(_context, this,
            calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH));
    dialog.show();

}

// updates the date in the birth date EditText
private void updateDisplay() {

    _editText.setText(new StringBuilder()
    // Month is 0 based so add 1
    .append(_day).append("/").append(_month + 1).append("/").append(_birthYear).append(" "));
}
}

Aussi quelque chose qui n'est pas mentionné dans les autres. Assurez-vous de mettre les éléments suivants sur EditText xml.

Android:focusable="false"

Sinon, comme dans mon cas, le clavier continuera à apparaître . J'espère que cela aidera quelqu'un

84
SatanEnglish
class MyClass implements OnClickListener, OnDateSetListener {   
   EditText editText;
   this.editText = (EditText) findViewById(R.id.editText);
   this.editText.setOnClickListener(this);
   @Override
   public void onClick(View v) {

       DatePickerDialog dialog = new DatePickerDialog(this, this, 2013, 2, 18);
       dialog.show();
   }
   @Override
   public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
       // this.editText.setText();
   }
}
21
Intathep

Il existe une autre meilleure façon réutilisable:

Créer une classe:

class setDate implements OnFocusChangeListener, OnDateSetListener {   

       private EditText editText;
       private Calendar myCalendar;

       public setDate(EditText editText, Context ctx){
           this.editText = editText;
           this.editText.setOnFocusChangeListener(this);
           myCalendar = Calendar.getInstance();
       }

       @Override
       public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)     {
           // this.editText.setText();

            String myFormat = "MMM dd, yyyy"; //In which you need put here
            SimpleDateFormat sdformat = new SimpleDateFormat(myFormat, Locale.US);
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            editText.setText(sdformat.format(myCalendar.getTime()));

       }

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
             new DatePickerDialog(ctx, this, myCalendar
                       .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                       myCalendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        }

    }

Appelez ensuite cette classe sous la fonction onCreate:

    EditText editTextFromDate = (EditText) findViewById(R.id.editTextFromDate);
    setDate fromDate = new setDate(editTextFromDate, this);
11
Sumoanand

Voici comment je procède: Similaire à la réponse choisie, mais en utilisant une classe de dialogue statique pour qu'elle soit plus réutilisable, et en utilisant également onFocusChange au lieu de onClick.

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                DialogFragment datePickerFragment = new DatePickerFragment() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int day) {
                        Log.d(TAG, "onDateSet");
                        Calendar c = Calendar.getInstance();
                        c.set(year, month, day);
                        editText.setText(df.format(c.getTime()));
                        nextField.requestFocus(); //moves the focus to something else after dialog is closed
                    }
                };
                datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
            }
        }
    });

Et la boîte de dialogue Datepicker.

public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
        //blah
    }
}
7
Daniel Jonker

La réponse sélectionnée ne fonctionnait pas tout à fait pour moi car je devais appuyer sur la case EditText une fois, puis à nouveau avant que l'OnClickListener ne se déclenche. J'ai pu résoudre ce problème en remplaçant OnClickListener par OnTouchListener, juste au cas où quelqu'un aurait rencontré un problème similaire, voici à quoi ressemble mon code:

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

};
edittext.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public void onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            new DatePickerDialog(classname.this, date, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    }
});

private void updateLabel() {

    String myFormat = "MM/dd/yy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

    edittext.setText(sdf.format(myCalendar.getTime()));
}
7
CodyEngel

#1. Je souhaite afficher un sélecteur de date avec la date actuelle présélectionnée (J'utilise butterknife pour l'injection)

  @OnClick(R.id.your_view) public void onClickYourView() {

    final 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);
        String myFormat = "dd MMMM yyyy"; // your format
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());

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

    };
    new DatePickerDialog(mContext, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();

  }

2. Si vous souhaitez présélectionner la date, remplacez la dernière partie par

new DatePickerDialog(mContext, date, 1990, 0, 1).show();

alors vous pouvez l'obtenir en utilisant la variable myCalendar ou directement le texte sur votre vue.

5
OWADVL
<EditText
    Android:id="@+id/date"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:ems="10"
    Android:hint="DD/MM/YYYY"
    Android:inputType="date"
    Android:focusable="false"/>

<EditText
    Android:id="@+id/time"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:hint="00:00"
    Android:inputType="time"
    Android:focusable="false"/>

Fichier Java

import Android.app.DatePickerDialog;
import Android.app.TimePickerDialog;
import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;
import Android.view.View;
import Android.widget.DatePicker;
import Android.widget.EditText;
import Android.widget.TimePicker;

import Java.util.Calendar;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    EditText selectDate,selectTime;
    private int mYear, mMonth, mDay, mHour, mMinute;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        selectDate=(EditText)findViewById(R.id.date);
        selectTime=(EditText)findViewById(R.id.time);

        selectDate.setOnClickListener(this);
        selectTime.setOnClickListener(this);




    }

    @Override
    public void onClick(View view) {

        if (view == selectDate) {
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);


            DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                    new DatePickerDialog.OnDateSetListener() {

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

                            selectDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

                        }
                    }, mYear, mMonth, mDay);
            datePickerDialog.show();
        }
        if (view == selectTime) {

            // Get Current Time
            final Calendar c = Calendar.getInstance();
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);

            // Launch Time Picker Dialog
            TimePickerDialog timePickerDialog = new TimePickerDialog(this,
                    new TimePickerDialog.OnTimeSetListener() {

                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay,
                                              int minute) {

                            selectTime.setText(hourOfDay + ":" + minute);
                        }
                    }, mHour, mMinute, false);
            timePickerDialog.show();
        }
    }
}
4
Mohsin Bhat

Ma classe pour le spectacle DatePicker. Je peux utiliser pour EditText, TextView ou Button

import Android.app.DatePickerDialog;
import Android.content.Context;
import Android.view.View;
import Android.widget.DatePicker;
import Android.widget.TextView;
import Java.text.SimpleDateFormat;
import Java.util.Calendar;
import Java.util.Date;
import Java.util.TimeZone;

public class TextViewDatePicker
        implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
    public static final String DATE_SERVER_PATTERN = "yyyy-MM-dd";
    private DatePickerDialog mDatePickerDialog;
    private TextView mView;
    private Context mContext;
    private long mMinDate;
    private long mMaxDate;

    public TextViewDatePicker(Context context, TextView view) {
        this(context, view, 0, 0);
    }

    public TextViewDatePicker(Context context, TextView view, long minDate, long maxDate) {
        mView = view;
        mView.setOnClickListener(this);
        mView.setFocusable(false);

        mContext = context;
        mMinDate = minDate;
        mMaxDate = maxDate;
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, monthOfYear);
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        Date date = calendar.getTime();

        SimpleDateFormat formatter = new SimpleDateFormat(DATE_SERVER_PATTERN);
        mView.setText(formatter.format(date));
    }

    @Override
    public void onClick(View v) {
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        mDatePickerDialog = new DatePickerDialog(mContext, this, calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        if (mMinDate != 0) {
            mDatePickerDialog.getDatePicker().setMinDate(mMinDate);
        }
        if (mMaxDate != 0) {
            mDatePickerDialog.getDatePicker().setMaxDate(mMaxDate);
        }
        mDatePickerDialog.show();
    }

    public DatePickerDialog getDatePickerDialog() {
        return mDatePickerDialog;
    }

    public void setMinDate(long minDate) {
        mMinDate = minDate;
    }

    public void setMaxDate(long maxDate) {
        mMaxDate = maxDate;
    }
}

En utilisant 

EditText myEditText = findViewById(R.id.myEditText);
TextViewDatePicker editTextDatePicker = new TextViewDatePicker(context, myEditText, minDate, maxDate);
//TextViewDatePicker editTextDatePicker = new TextViewDatePicker(context, myEditText); //without min date, max date
3
Linh

Une solution utilisant des fragments, MvvmCross et Xamarin.Android

public class EnterTimeView : MvxFragment, DatePickerDialog.IOnDateSetListener
    {            
        private EditText datePickerText;
        public EnterTimeView()
        {
            this.RetainInstance = true;
        }

        public override Android.Views.View OnCreateView(Android.Views.LayoutInflater inflater, Android.Views.ViewGroup container, Android.OS.Bundle savedInstanceState)
        {
            this.HasOptionsMenu = true;

            var ignored = base.OnCreateView(inflater, container, savedInstanceState);
            var view = inflater.Inflate(Resource.Layout.EnterTimeView, container, false);

            datePickerText = view.FindViewById<EditText>(Resource.Id.DatePickerEditText);
            datePickerText.Focusable = false;
            datePickerText.Click += delegate
            {
                var dialog = new DatePickerDialogFragment(Activity, Convert.ToDateTime(datePickerText.Text), this);
                dialog.Show(FragmentManager, "date");
            };

            var set = this.CreateBindingSet<EnterTimeView, EnterTimeViewModel>();    
            set.Bind(datePickerText).To(vm => vm.Date);
            set.Apply();

            return view;
        }   

        public void OnDateSet(Android.Widget.DatePicker view, int year, int monthOfYear, int dayOfMonth)
        {
            datePickerText.Text = new DateTime(year, monthOfYear + 1, dayOfMonth).ToString();
        }

        private class DatePickerDialogFragment : Android.Support.V4.App.DialogFragment 
        {
            private readonly Context _context;
            private DateTime _date;
            private readonly DatePickerDialog.IOnDateSetListener _listener;

            public DatePickerDialogFragment(Context context, DateTime date, DatePickerDialog.IOnDateSetListener listener)
            {
                _context = context;
                _date = date;
                _listener = listener;
            }

            public override Dialog OnCreateDialog(Bundle savedState)
            {
                var dialog = new DatePickerDialog(_context, _listener, _date.Year, _date.Month - 1, _date.Day);
                return dialog;
            }
        }
3
ben
 selectDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DatePickerDialog  mdiDialog =new DatePickerDialog(mContext,new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        Toast.makeText(getApplicationContext(),year+ " "+monthOfYear+" "+dayOfMonth,Toast.LENGTH_LONG).show();


                    }
                }, year, month, date);
                mdiDialog.show();

            }

        });
3
erluxman

Utilisation de DataBinding:

<EditText
  Android:layout_width="wrap_content"
  Android:layout_height="wrap_content"
  Android:focusable="false"
  Android:onClick="@{() -> viewModel.onDateEditTextClicked()}"
  Android:hint="@string/hint_date"
  Android:imeOptions="actionDone"
  Android:inputType="none"
  Android:maxLines="1"
  Android:text="@={viewModel.filterDate}" />

(voir focusable, inputType et onClick)

À l'intérieur ViewModel:

public void onDateEditTextClicked() {
    // do something
}
3
Matias Elorriaga

J'ai essayé tous les moyens qui ont été suggérés, mais tous ont leurs propres problèmes.

La meilleure solution à mon avis serait d'utiliser une disposition du cadre comme ci-dessous:

<FrameLayout
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content" >

            <EditText
                Android:layout_width="match_parent"
                Android:layout_height="wrap_content"
                .... />

            <View
                Android:id="@+id/invisible_click_watcher"
                Android:layout_width="match_parent"
                Android:layout_height="match_parent"
                Android:clickable="true" />

</FrameLayout>

puis en ajoutant le code DatePickerDialog qui était magnifiquement écrit dans la réponse de @ Android.

2
mehrdadjg

Essaye ça

btn=(Button)findViewById(R.id.chs);
    final Dialog dialog = new Dialog(MainActivity.this);
    dialog.setCanceledOnTouchOutside(true);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.setContentView(R.layout.datepickerdialog);
            dp=(DatePicker) dialog.findViewById(R.id.btp);
            dialog.show();
            ok=(Button)dialog.findViewById(R.id.btn1);
            ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        }

    });
1
Swapnil Ankushe

editText.setOnClickListener (new View.OnClickListener () {

    @Override
    public void onClick(final View v) {
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);


        final DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
                new DatePickerDialog.OnDateSetListener() {
                    String fmonth, fDate;
                    int month;


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


                        try {
                            if (monthOfYear < 10 && dayOfMonth < 10) {

                                fmonth = "0" + monthOfYear;
                                month = Integer.parseInt(fmonth) + 1;
                                fDate = "0" + dayOfMonth;
                                String paddedMonth = String.format("%02d", month);
                                editText.setText(fDate + "/" + paddedMonth + "/" + year);

                            } else {

                                fmonth = "0" + monthOfYear;
                                month = Integer.parseInt(fmonth) + 1;
                                String paddedMonth = String.format("%02d", month);
                                editText.setText(dayOfMonth + "/" + paddedMonth + "/" + year);
                            }


                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }

                }, mYear, mMonth, mDay);
        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
        datePickerDialog.show();


    }


});
1
Jaimin Mehta
import Android.app.DatePickerDialog;
import Android.content.Context;
import Android.view.View;
import Android.widget.DatePicker;
import Android.widget.TextView;

import Java.text.SimpleDateFormat;
import Java.util.Calendar;
import Java.util.Locale;

public class DatePickerHelper {

private final Calendar calendar = Calendar.getInstance();
private final String dateFormat = "MM/dd/yy";
private TextView textView = null;

public DatePickerHelper(final Context context, TextView textView) {
    this.textView = textView;

    // Setup on click listener if the TextView is not null
    if (textView != null) {
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDatePickerDialog(context).show();
            }
        });
    }
}

/**
 * Return a new date picker listener tied to the specified TextView field
 * @return
 */
private DatePickerDialog.OnDateSetListener getOnDateSetListener() {
    return new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, monthOfYear);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.US);
            textView.setText(sdf.format(calendar.getTime()));
        }
    };
}

/**
 * Return new DatePickerDialog for field
 * @param context
 * @return
 */
private DatePickerDialog getDatePickerDialog(Context context) {
    return new DatePickerDialog(context, getOnDateSetListener(), calendar
            .get(Calendar.YEAR), calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH));
}

}

Usage:

  DatePickerHelper assessmentDueDateHelper = new DatePickerHelper(AssessmentsDetailActivity.this,
            (TextView) findViewById(R.id.assessmentDueDateEditText));
1
Brad Hasha

Je pensais qu'il était préférable de remplacer la classe EditText ...

public class EditTextDP extends Android.support.v7.widget.AppCompatEditText implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
    public EditTextDP(Context context) {
        super(context);
        setOnClickListener(this);
        setFocusable(false);
    }

    public EditTextDP(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(this);
        setFocusable(false);
    }

    public EditTextDP(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOnClickListener(this);
        setFocusable(false);
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        setText(new StringBuilder().append(dayOfMonth).append("/").append(monthOfYear + 1).append("/").append(year));
    }

    @Override
    public void onClick(View v) {
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        DatePickerDialog dialog = new DatePickerDialog(getContext(), this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }
}

Et utilisez cela dans le XML à la place ...

            <*.*.*.EditTextDP
                Android:id="@+id/c1_dob_hm"
                Android:layout_width="match_parent"
                Android:layout_height="wrap_content"
                Android:background="@drawable/round_edittext_white"
                Android:ems="10"
                Android:padding="8dp">

            </*.*.*.EditTextDP>
1
Mark Proctor

Utilisez ceci

your_edittext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {

                    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);
                    DatePickerDialog datePicker = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            String date = String.valueOf(dayOfMonth) + "/" + String.valueOf(monthOfYear+1)
                                    + "/" + String.valueOf(year);
                            your_edittext.setText(date);
                        }
                    }, yy, mm, dd);
                    datePicker.show();
                }
            });
1
domini ccqque

Port Kotlin, appelez la fonction setDatePicker

private fun setDatePicker(dateEditText: EditText) {

val myCalendar = Calendar.getInstance()

        val datePickerOnDataSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
            myCalendar.set(Calendar.YEAR, year)
            myCalendar.set(Calendar.MONTH, monthOfYear)
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
            updateLabel(myCalendar, dateEditText)
        }

        dateEditText.setOnClickListener {
            DatePickerDialog(this@EditDetailActivity, datePickerOnDataSetListener, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH)).show()
        }
    }

    private fun updateLabel(myCalendar: Calendar, dateEditText: EditText) {
        val myFormat: String = "dd-MMM-yyyy"
        val sdf = SimpleDateFormat(myFormat, Locale.UK)
        dateEditText.setText(sdf.format(myCalendar.time))
    }
1
Karats Mohanraj

Ne pas oublier de définir attributs de Edittext comme suit:

Android:clickable="true"
Android:focusable="false"
0
Ahmed Shokry

fonctionne bien pour moi

Je définis dans la vue EditText

Android:focusable="false"
0
Deepak
    EditText text = (EditText) findViewById(R.id.editText);

    text.setOnClickListener(new OnClickListener(){
       @RequiresApi(api = Build.VERSION_CODES.N)
       @Override
       public void onClick(View view) {

             DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
               @Override
               public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                   String date = i2 + "/" + (++i1) + "/" + i;
                   text.setText(date);
                }
        },year,month,date);
       }
    });  

    datePickerDialog.show();

vous pouvez également définir la date minimale et la date maximale à l'aide de ces instructions.

   datepickerDialoge.getDatepicker().setMinDate(long Date);

   datepickerDialoge.getDatepicker().setMaxDate(long Date);

Remarque: ajoutez ces lignes avant datepickerDialog.show (); déclarationvous obtiendrez la date comme ceci = 12/2/2017.

J'espère que ma réponse aidera. 

0
Siva krishna

Ma solution pour Xamarin.Android avec MvvmCross basée sur Linh:

public class DatePickerEditText : EditText, DatePickerDialog.IOnDateSetListener
{
    IDisposable _clickSubscription;

    public override bool Clickable => true;

    protected DatePickerEditText(IntPtr javaReference, JniHandleOwnership transfer)
        : base(javaReference, transfer)
        => Init();

    public DatePickerEditText(Context context) : base(context)
        => Init();

    public DatePickerEditText(Context context, IAttributeSet attrs) 
        : base(context, attrs)
        => Init();

    public DatePickerEditText(Context context, IAttributeSet attrs, int defStyleAttr) 
        : base(context, attrs, defStyleAttr)
        => Init();

    public DatePickerEditText(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) 
        : base(context, attrs, defStyleAttr, defStyleRes)
        => Init();

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _clickSubscription?.Dispose();
            _clickSubscription = null;
        }

        base.Dispose(disposing);
    }

    public void OnDateSet(DatePicker view, int year, int month, int dayOfMonth)
        => Text = view.DateTime.ToString("d", CultureInfo.CurrentUICulture);

    void Init()
    {
        SetFocusable(ViewFocusability.NotFocusable);
        _clickSubscription = this.WeakSubscribe(nameof(Click), OnClick);
    }

    void OnClick(object sender, EventArgs e)
    {
        var date = DateTime.Today;
        try
        {
            date = DateTime.Parse(Text, CultureInfo.CurrentUICulture);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex);
        }

        var dialog = new DatePickerDialog(Context,
                                          this,
                                          date.Year,
                                          date.Month,
                                          date.Day);
        dialog.Show();
    }
}

Pour une version Vanilla Xamarin.Android, il suffit de remplacer WeakSubscribe par un abonnement régulier à l'événement Click d'EditText, sans oublier de vous désabonner du remplacement de la méthode Dispose.

0
Rafael Pereira
public class DatePickerActivity extends AppCompatActivity {
    Button button;
    static TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button= (Button) findViewById(R.id.btn_click);
        textView= (TextView) findViewById(R.id.txt_date);



        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment newFragment=new DatePickerFragment();
                newFragment.show(getFragmentManager(), "datepicker");
            }
        });

    }

    public class DatePickerFragment extends DialogFragment implements    DatePickerDialog.OnDateSetListener{
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int  day) {
            String years=""+year;
            String months=""+(monthOfYear+1);
            String days=""+day;
            if(monthOfYear>=0 && monthOfYear<9){
                months="0"+(monthOfYear+1);
            }
            if(day>0 && day<10){
                days="0"+day;

            }
            textView.setText(days+"/"+months+"/"+years);


        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            //use the current date as the default date in the picker
            final Calendar c=Calendar.getInstance();
            int year=c.get(Calendar.YEAR);
            int month=c.get(Calendar.MONTH);
            int day=c.get(Calendar.DAY_OF_MONTH);
            DatePickerDialog datePickerDialog=null;
            datePickerDialog=new DatePickerDialog(getActivity(), this, year,  month, day);

            return datePickerDialog;
        }

    }

}
0
Rohit Das

Utilisez cette technique simple pour le faire:

_ {Étape 1: CRÉER UN DIALOGUE DE FRAGMENT} _

public class DatePickerFragmentDialog  extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day);
    }

}

_ {Étape 2: SUITE À L'ACTIVITÉ REQUISE

  1. L'activité doit implémenter: DatePickerDialog.OnDateSetListener

  2. Définir onClickListener sur un bouton:

    DialogFragment datePicker = new DatePickerFragmentDialog();
    datePicker.show(getSupportFragmentManager(), "Custom Date Picker");
    

Étape 3: remplacement de OnDateSetListener

public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

        @SuppressLint("SimpleDateFormat") DateFormat dateFormat = new 
        SimpleDateFormat("MM/dd/yyyy");
        String currentDateString = dateFormat.format(calendar.getTime());

        tvPaymentDate.setText(currentDateString);
    }

Nous pouvons donc utiliser n'importe quelle mise en forme pour la date :)

0

Essaye ça:

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

DataPickerListener listener;

public DatePickerFragment(DataPickerListener l) {
    listener = l;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the date picker
    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);

    return new DatePickerDialog(getActivity(),
            AlertDialog.THEME_HOLO_LIGHT, this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {

    month = month + 1;
    String stringOfDate = day + "-" + month + "-" + year;
    listener.setDate(stringOfDate);
    Util.Log(stringOfDate);
}

@Override
public void onCancel(DialogInterface dialog) {
    // TODO Auto-generated method stub
    super.onCancel(dialog);
    listener.cancel();
}

public static interface DataPickerListener {
    void setDate(String date);

    void cancel();
}
}
// use this function to open datePicker popup

DialogFragment newFragment;

public void pickDate() {
    if (newFragment == null)
        newFragment = new DatePickerFragment(new PickDateListener());
    newFragment.show(getFragmentManager(), "Date Picker");
}

class PickDateListener implements DataPickerListener {

    @Override
    public void setDate(String date) {
        createSpiner(date);
        onetouch = false;
    }

    @Override
    public void cancel() {
        onetouch = false;
    }

}
0
DILSHAD AHMAD
editText1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            DatePickerDialog.OnDateSetListener dpd = new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear,
                                      int dayOfMonth) {

                    int s = monthOfYear + 1;
                    String a = dayOfMonth + "/" + s + "/" + year;
                    editText1.setText(a);
                }
            };

            Time date = new Time();
            DatePickerDialog d = new DatePickerDialog(UpdateStore.this, dpd, date.year, date.month, date.monthDay);
            d.show();

        }
    });
0
Praveen

Si vous ne voulez pas gâcher votre activité ou votre fragment avec la logique du sélecteur de date et souhaitez simplement ouvrir une boîte de dialogue de sélection de date et obtenir un rappel après la date sélectionnée, vous pouvez consulter ma réponse ici.

Ma réponse: comment faire apparaître un datepicker lorsqu’il clique sur edittext dans fragment

0
Sayan Mukherjee

Boîte de dialogue Date Picker

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

                DatePickerDialog datePickerDialog =new DatePickerDialog(Expenture_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        et_from.setText(dayOfMonth+"/"+month+"/"+year);
                    }
                },day,month,year);
                datePickerDialog.show();
0
Ankush Shrivastava