I'm learning about screen rotation for an App, I came across this example and I tried it.
My issue is that when I try this with a Button widget, it's text is still blank. When the button is clicked a date picker dialog appears to pick a date. But if the screen is rotated after the selection is made, the previously selected date is lost.
This is my code:
startDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setDate(startDate);
}
});
public void setDate(final Button B)
{
final Calendar calender = Calendar.getInstance();
day = calender.get(Calendar.DAY_OF_MONTH);
month = calender.get(Calendar.MONTH);
year = calender.get(Calendar.YEAR);
DatePickerDialog pickDate = new DatePickerDialog(add_event.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
calender.set(i,i1,i2);
SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd-MM-yyyy");
String dateString = dateFormat1.format(calender.getTime());
B.setText(dateString);
}
},year,month,day);
pickDate.show();
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putString("startDate", startDate.getText().toString());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
startDate.setText(savedInstanceState.getString("startDate"));
}
Here are some images: