我创建了一个由按钮触发的DatePickerFragment。选择日期后,该日期将显示在TextView中。
DatePickerFragment可以按预期工作,但是每次打开它时,它都会显示当前日期,而不是最后选择的日期。
用例
我们将为您提供解决此问题的任何帮助。
这是我的代码
MyActivity.java
// DATE PICKER
dateBoughtButton = findViewById(R.id.date_bought_button);
dateTextView = findViewById(R.id.date_bought_text_view);
// Defining Date Format
final String format = Settings.System.getString(getContentResolver(), Settings.System.DATE_FORMAT);
final DateFormat dateFormat;
if (isEmpty(format)) {
dateFormat = android.text.format.DateFormat.getMediumDateFormat(getApplicationContext());
} else {
dateFormat = new SimpleDateFormat(format);
}
// Creating Calendar object
Calendar selectedDate = Calendar.getInstance();
// Creating Bundle
final Bundle args = new Bundle();
args.putInt("year", selectedDate.get(Calendar.YEAR));
args.putInt("month", selectedDate.get(Calendar.MONTH));
args.putInt("day", selectedDate.get(Calendar.DAY_OF_MONTH));
dateBoughtButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.setArguments(args);
newFragment.show(getFragmentManager(), "date picker");
newFragment.setCallBack(onDate);
}
DatePickerDialog.OnDateSetListener onDate = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
dateTextView.setText(dateFormat.format(newDate.getTime()));
}
};
});
DatePickerFragment.java
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
DatePickerDialog.OnDateSetListener onDateSet;
int year, month, day;
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), onDateSet, year, month, day);
}
public void setCallBack(DatePickerDialog.OnDateSetListener onDate) {
onDateSet = onDate;
}
@Override
public void setArguments(Bundle args) {
super.setArguments(args);
year = args.getInt("year");
month = args.getInt("month");
day = args.getInt("day");
}
}