So, before editing code, lets prepare GUI for this. In UI xml file, make sure to have a trigger for event of entering the date. In this example we will insert a button which will normally show actual date, but the user can change the date any time he/she wants.
Most of coding goes to activity file. First of all, we have to instance new button, and place an onClickListener on it.
Afterwards make sure you have instantiated private attributes and set them on right values (which are actual date, at the beginning). You can do it along with all the others necessary private attributes:
Afterward, make sure you set attributes to right default values:
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
updateDisplay();
updateDisplay() is a custom method used to make a string out of numeric values of year, month and date. And along the way, it corrects the months because they start with zero.
private void updateDisplay() {
//add +1 to month, because months start with zero
date = pad(mDay)+"."+pad(mMonth+1)+"."+pad(mYear);
button_odaberiDatum.setText(date);
}
pad(int c) is a custom method used to return string values instead of integers.
private String pad(int c) {
if (c>=10)
return String.valueOf(c);
else
return ("0"+String.valueOf(c));
}
Afterwards, we need to instantiate DatePickerDialog within onCreateDialog method, with onDateSetListener implementing onDateSet method, which is done as follows:
@Override
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 OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};
And that's it.
Nema komentara:
Objavi komentar