如何创建自定义材料对话框

时间:2016-05-22 11:22:25

标签: android dialog material-design alertdialog

我想知道如何为我的应用程序创建自定义材质对话框。具体来说,我需要实现这样的目标

Material Dialog

我一直在按照这种方式关注旧方法:

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

但是,在点击button时我得到了空指针异常。任何教程对我都有很大的帮助。

2 个答案:

答案 0 :(得分:7)

编写一个扩展到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();
        }
    };

}

然后从您的活动中调用它

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

希望,它会奏效。

答案 1 :(得分:0)

我认为你应该创建自己的类来扩展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();
}

并在您的活动中使用此代码显示对话框

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