how to set date in edit text
android, datepicker
Solution
Define editText and Button in xml and below code in your activity:
editText=(EditText) findViewById(R.id.date);
button=(Button) findViewById(R.id.play);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
Calendar c=Calendar.getInstance();
mYear=c.get(Calendar.YEAR);
mMonth=c.get(Calendar.MONTH);
mDay=c.get(Calendar.DAY_OF_MONTH);
Now add these two functions to call DatePicker Dialog and to set date in the Edittext
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener =new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
editText.setText(new StringBuilder().append(mDay).append("/").append(mMonth+1).append("/").append(mYear));
}
};
Define this globally:
static final int DATE_DIALOG_ID = 0;
private int mYear,mMonth,mDay;
This will help you to set date in the editText.Hope this will help you.
Problem
i have a edit text box and i have call ontouchlistener it show a custom dialog and when i click setdate button the date on date picker should set on the edit text and the dialog should get dismiss. but i dont know how to get date from date picker and how to set in edit text box. i am getting error in date.init( year, monthOfYear, dayOfMonth, new MyOnDateChangedListener() ); and the error isMultiple markers at this line - dayOfMonth cannot be resolved to a variable - year cannot be resolved to a variable - monthOfYear cannot be resolved to a variable ``` et4.setOnTouchListener(new OnTouchListener() { final Dialog setdatedialog = new Dialog(DropboxActivity.this); public void onClick(View v) { } public boolean onTouch(View arg0, MotionEvent arg1) { setdatedialog.setContentView(R.layout.datedialog); setdatedialog.setTitle("select date of puchase"); setdatedialog.setCancelable(true); setdatedialog.show(); Button back = (Button)setdatedialog.findViewById(R.id.back3); back.setOnClickListener(new OnClickListener() { public void onClick(View v) { setdatedialog.dismiss(); } }); Button setdate=(Button)setdatedialog.findViewById(R.id.setdate); DatePicker date = (DatePicker)setdatedialog.findViewById(R.id.datePicker1); class MyOnDateChangedListener implements OnDateChangedListener { public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth){ et4.setText( "" + dayOfMonth + "-" + (monthOfYear + 1) + "-" + year ); } }; date.init( year, monthOfYear, dayOfMonth, new MyOnDateChangedListener() ); return false; } ```