Reputation: 115
I have an AlertDialog
which includes a button to initiate a DatePicker
. Is it possible to accomplish this within a dialog and if so how would I go about it?
I have searched Google and several posts on SO but have been unable to find information on accomplishing a DatePicker
within an Alert Dialog
.
Upvotes: 2
Views: 1075
Reputation: 6345
Without seeing your code, it is difficult to Guess where is an Error, but you may try below code:
public class MainActivity extends ActionBarActivity implements DatePickerDialog.OnDateSetListener {
Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set your Alert Dialog box code
mContext=this;
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("This is Alert dialog messgae")
.setTitle("Launch the date Picker")
.setPositiveButton("Date Pick", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Launch a date picker from Here
showDatePickerDialog();
}
})
.setNegativeButton("cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Cancel the Dialog itself
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public void showDatePickerDialog() {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
private static class DatePickerFragment extends DialogFragment {
@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);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), (OnDateSetListener) getActivity(), year, month, day);
}
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
}
}
As you can see, I am creating a Date Picker using Fragment on click of Alert Dialog Button.
Your Activity needs to implement
onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth)
Otherwise App crashes with an java.lang.ClassCastException
with below error message :
MainActivity$DatePickerFragment cannot be cast to android.app.DatePickerDialog$OnDateSetListener
Upvotes: 1
Reputation: 30985
AlertDialog is just for alert messages. Use Dialog and you can set your own content view.
Upvotes: 0