android – How to create custom Material Dialog-ThrowExceptions

Exception or error:

I would like to know how to create custom material dialog for my application. Specifically, I need to achieve something like this

Material Dialog

I have been following old method like this way:

final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Sample");
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
            // if button is clicked, close the custom dialog
            dialogButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });

However, I got null pointer exception while tapping the button. Any tutorial will be also a great help for me.

How to solve:

Write a new class that extends to DialogFragment.

public class CustomDialog extends DialogFragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_dialog,container,false);
        getDialog().setTitle("Sample");
        Button doneBtn = (Button) mView.findViewById(R.id.done_convert);
        doneBtn.setOnClickListener(doneAction);
        return view;
    }

    View.OnClickListener doneAction = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(),"Test",Toast.LENGTH_LONG).show();
        }
    };

}

Then call it from your activity

FragmentManager fm = getSupportFragmentManager();
CustomDialog custom = new CustomDialog();
custom.show(fm,"");

Hope, it will work.

###

I think you should make your own class which extends DialogFragment

public class YourDialog extends DialogFragment {

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {

    LayoutInflater inflater = getActivity().getLayoutInflater();
    final View dialogView = inflater.inflate(R.layout.custom, null);

    Button dialogButton = (Button) dialogView.findViewById(R.id.dialogButtonOK);
        // if button is clicked, close the custom dialog
        dialogButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(dialogView);
    return builder.create();
}

and in your activity use this code to show the dialog

YourDialog yourDialog = new YourDialog();
yourDialog.show(getFragmentManager(), "YOUR_DIALOG_TAG");

Leave a Reply

Your email address will not be published. Required fields are marked *