noel293
noel293

Reputation: 504

LayoutInflater with DatePicker Dialog

I am trying to set an editText with a DatePickerDialog inside a .setOnClickListener. where, when the user clicks on the editText the DatePickerDialog will appear and then after the user selects the desirable date it will set it on the editText... something like this : Android:DatePickerDialog on EditText Click Event

and here is my code mycode

Any ideas how to do that?

I tried the above example and many more but nothing seems to work inside the .SetOnClickListener

Upvotes: 0

Views: 108

Answers (1)

Pial Kanti
Pial Kanti

Reputation: 1610

Use this code:

public class MainActivity extends AppCompatActivity {
EditText text;
private int year,currentYear;
private int month,currentMonth;
private int day,currentDay;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    text = (EditText)findViewById(R.id.edit);

    // 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);

    text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker datePicker, int mYear, int mMonth, int mDay) {
                    currentDay = mDay;  
                    currentMonth = mMonth+1;
                    currentYear = mYear;
                    text.setText(mDay+"-"+(mMonth+1)+"-"+mYear);
                }
            },year,month,day).show();
        }
    });
}

}

I have store the user selected year, month, day in currentYear,currentMonth,currentDay respectively.

Upvotes: 1

Related Questions