John John - 16 days ago 6
Android Question

Set DatePickerDialog title permanently

I have a problem when I'm trying to set DatePickerDialog title permanently.

DatePickerFragment.java

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
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);

// Create a new instance of DatePickerDialog and return it
DatePickerDialog dpd = new DatePickerDialog(getActivity(), this, year, month, day);
dpd.setTitle("set date");
return dpd;
}

public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}


MainActivity.java

public class MainActivity extends FragmentActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button btn = (Button) findViewById(R.id.button1);

btn.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");

}
});
}
}


When I click button DatePickerDialog shows and dialog title is "set date" but when I change date, title contains selected date rather than "set date". How can I set this dialog title permanently?

Tested on API 8-10.

Thank you in advance and sorry for my English. Patrick

Answer

How about extending DatePickerDialog and adding a setPermanentTitle method to store a permanent title that will be forced when date gets changed ?

public class MyDatePickerDialog extends DatePickerDialog {

    private CharSequence title;

    public MyDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
        super(context, callBack, year, monthOfYear, dayOfMonth);
    }

    public void setPermanentTitle(CharSequence title) {
        this.title = title;
        setTitle(title);
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int month, int day) {
        super.onDateChanged(view, year, month, day);
        setTitle(title);
    }
}

And then use the new setPermanentTitle method:

    MyDatePickerDialog dpd = new MyDatePickerDialog(this, null, 2012, 10, 10);
    dpd.setPermanentTitle("set date");