Reputation: 13450
As you can see in the code below I have tried to add a neutral button which sets the query_date
and dismisses the dialog. Unfortunately this below does not work: the neutral button is not displayed at all.
I want to have a middle button called "today" and does that action.
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setNeutralButton("Today", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
query_date = now_date;
dialog.dismiss();
}
});
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
dialog.getDatePicker().setMinDate(c.getTimeInMillis() );
return dialog;
}
@SuppressLint("SimpleDateFormat")
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
TimeZone tz = TimeZone.getDefault();
SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
sdfSource.setTimeZone(tz);
Date date = new GregorianCalendar(year,month,day).getTime();
SimpleDateFormat sdfDestination = new SimpleDateFormat("EEE', 'd LLL");
query_date = sdfSource.format(date);
change_date_button.setText(sdfDestination.format(date));
load_more_bar.setVisibility(View.VISIBLE);
new get_events().execute();
}
}
The way I call the DialogFragment from a onClick button listener is below:
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getActivity().getFragmentManager(), "datePicker");
Is it possible to have a neutral button in a DatePickerDialog
Fragment? If so how?
Upvotes: 1
Views: 2377
Reputation: 12229
You are instantiating two Dialogs. One AlertDialog and another DatePickerDialog. You should use only one:
@Override public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
dialog.getDatePicker().setMinDate(c.getTimeInMillis() );
dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "Today", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
query_date = now_date;
dialog.dismiss();
}
});
return dialog;
}
Upvotes: 1