Skip to content Skip to sidebar Skip to footer

Custom Dialog Fragment

I am trying to create a simplistic dialog similar to a DatePickerDialog. The Dialog that I am creating should provide the user with an array of images from which they can select. I

Solution 1:

If the activity in which you want to open the DialogFragment extends FragmentActivity, you should execute:

PicturePickerFragmentdialog=newPicturePickerFragment();
dialog.show(getSupportFragmentManager(), "YourDialog");

Also you need to inflate your dialog layout file in the method onCreateDialog of your dialog fragment class.

Using AlertDialog.Builder you can achieve all this easily, e.g.

AlertDialog.Builderbuilder=newAlertDialog.Builder(getActivity());

LayoutInflaterinflater= getActivity().getLayoutInflater();

// Inflate and set the layout for the dialog// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialoglayout, null))
 .setTitle(R.string.dialog_title)
 .setPositiveButton(R.string.pos_button, newDialogInterface.OnClickListener() {
    @OverridepublicvoidonClick(DialogInterface dialog, int which) {
        // call the method on the parent activity when user click the positive button
    }
})
 .setNegativeButton(R.string.neg_button, newDialogInterface.OnClickListener() {
    @OverridepublicvoidonClick(DialogInterface dialog, int which) {
        // call the method on the parent activity when user click the negative button
    }
});
return builder.create();

There are many examples on http://developer.android.com/reference/android/app/DialogFragment.html

Solution 2:

There are different ways you can create your dialog either using OnCreateView method or using OnCreateDialog method if you are extending the DialogFragment class and so the implementation goes in a different way for both.

You should return your Dialog instance from OnCreateDialog method.

How to show the dialog in a Activity

FragmentTransactionft= getFragmentManager().beginTransaction();
 Fragmentprev= getFragmentManager().findFragmentByTag("YourFragmentID");

 if (prev != null) {
        ft.remove(prev);
    }
 ft.addToBackStack(null);

 PicturePickerFragmentpf=newPicturePickerFragment();
 pf.show();

May be you can refer to this link which is a nice example from official AndroidDeveloper's site.

Post a Comment for "Custom Dialog Fragment"