androidandroid-fragmentsandroid-calendar

Best way to select date from a calendar and display it in the TextView


I have searched a lot and need to know the best way possible to select a date from a calendar, I am already trying a fragment such as

FragmentManager manager=getFragmentManager(); FragmentTransaction transaction=manager.beginTransaction();

DialogFragment fragment=new DatePickerDialogFragment(MainActivity.this); fragment.show(transaction, "date_dialog");

but have errors regarding imports , as they are conflicting i believe... really need a way out, does anyone have a good solution , please do let me know i need it!


Solution

  • I like to do this with Dialog. First of all, set android:focusable="false" on your EditText in your xml.

    Then you can try something like this:

    yourEditText = (EditText) findViewById(R.id.yourEditTextID);
            yourEditText.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    // To show current date in the datepicker
                    Calendar mcurrentDate = Calendar.getInstance();
                    mYear = mcurrentDate.get(Calendar.YEAR);
                    mMonth = mcurrentDate.get(Calendar.MONTH);
                    mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);
    
                    DatePickerDialog mDatePicker = new DatePickerDialog(yourActivity.this, new OnDateSetListener() {
                        public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
                            Calendar myCalendar = Calendar.getInstance();
                            myCalendar.set(Calendar.YEAR, selectedyear);
                            myCalendar.set(Calendar.MONTH, selectedmonth);
                            myCalendar.set(Calendar.DAY_OF_MONTH, selectedday);
                            String myFormat = "dd/MM/yy"; //Change as you need
                            SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.FRANCE);
                            yourEditText.setText(sdf.format(myCalendar.getTime()));
    
                            mDay = selectedday;
                            mMonth = selectedmonth;
                            mYear = selectedyear;
                        }
                    }, mYear, mMonth, mDay);
                    //mDatePicker.setTitle("Select date");
                    mDatePicker.show();
                }
            });
    

    Where mYear,mMonth and mDay are global int.