【问题标题】:Am I doing it correctly?我做对了吗?
【发布时间】:2017-09-28 01:59:02
【问题描述】:

我正在学习和记住 Android,我想了解我的错误。 这是我的确认/取消 AlertDialog 类。在单独的类中创建它以拆分代码,而不是将所有内容放在一个 Activity 中:

public class ConversationAlertDialog extends DialogFragment {

    public static Dialog createDialog(Context context) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        builder.setMessage("Continue?")
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User confirms

                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User cancelled
                    }
                });
        // Create the AlertDialog object and return it
        return builder.create();
    }
}

这是我显示 AlertDialog 的 Activity:

    buttonConvert.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            ConversationAlertDialog.createDialog(ConversionActivity.this).show();
        }
    });

接下来我想创建回调,这样我就可以在 Activity 中编写对话框取消/确认行为。这样,使用 Activity 中已经编写的代码也会更容易。我还在学习回调所以不确定,但我认为我应该实现接口。

各种提示都会对我有所帮助。

【问题讨论】:

    标签: android callback android-alertdialog


    【解决方案1】:

    他是我使用的代码。我发现它非常灵活,因为您可以为稍微不同的任务创建几个类似的对话框。您将需要创建一个布局文件 - 这为您在功能和样式方面提供了极大的灵活性。

    我的布局文件是fragment_ok_cancel_dialog

    在调用对话框的 Activity 中,您需要实现 Listener。

    implements OkCancelDialogFragment.OkCancelDialogListener
    

    另一个优点是使用我的代码,您可以更改标题和消息以适应任何活动的需要。

    private void callMyDialog(){ 
        //Customize the title and message as needed
        String title = "This is my dialog title";
        String mess = "This is my dialog message";
        OkCancelDialogFragment dialog = OkCancelDialogFragment.newInstance(title, mess);
        dialog.show(getFragmentManager(), "OkCancelDialogFragment2");
    }
    

    现在需要在调用DialogFragment的Activity中实现对话框回调。

    @Override
    public void onFinishOkCancelDialog(boolean submit) {
        if(submit){
            // Do something positive
        }
        else{
            // Do something negative
        }
    }
    

    现在是DialogFragment的代码:

    public class OkCancelDialogFragment extends DialogFragment {
    
        private static final String ARG_TITLE = "title";
        private static final String ARG_MESSAGE = "message";
    
        Context context = null;
    
        private String title;
        private String message;
        private boolean submitData = false;
    
        private OkCancelDialogListener mListener;
    
        public OkCancelDialogFragment() {
        }
    
        public static OkCancelDialogFragment newInstance(String title, String message) {
            OkCancelDialogFragment fragment = new OkCancelDialogFragment();
            Bundle args = new Bundle();
            args.putString(ARG_TITLE, title);
            args.putString(ARG_MESSAGE, message);
            fragment.setArguments(args);
            return fragment;
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getArguments() != null) {
                title = getArguments().getString(ARG_TITLE);
                message = getArguments().getString(ARG_MESSAGE);
            }
        }
    
        @Override
        public Dialog onCreateDialog(Bundle saveIntsanceState){
    
            context = getActivity();
    
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    
            LayoutInflater inflater = getActivity().getLayoutInflater();
    
            View rootView = inflater.inflate(R.layout.fragment_ok_cancel_dialog, null, false);
            final TextView titleView = (TextView)rootView.findViewById(R.id.tvTitle);
            final TextView messView = (TextView)rootView.findViewById(R.id.tvMessage);
    
            titleView.setText(title);
            messView.setText(message);
    
            builder.setView(rootView)
    //                .setTitle(title)
                    .setPositiveButton(R.string.ok_button_dialog_title, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
    
                            submitData = true;
                            if(mListener == null) mListener = (OkCancelDialogListener) context;
                            mListener.onFinishOkCancelDialog(submitData);
                        }
                    })
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            submitData = false;
                            if(mListener == null) mListener = (OkCancelDialogListener) context;
                            mListener.onFinishOkCancelDialog(submitData);
                        }
                    });
            return builder.create();
        }
    
    
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            try {
                if(mListener == null) mListener = (OkCancelDialogListener) context;
            }
            catch (Exception ex){
                throw new RuntimeException(context.toString()
                        + " must implement OnFragmentInteractionListener");
            }
        }
    
        @Override
        public void onDetach() {
            super.onDetach();
            mListener = null;
        }
    
    
        public interface OkCancelDialogListener {
            void onFinishOkCancelDialog(boolean submit);
        }
    
    }
    

    请注意.setTitle(title) 适用于 API 23 或更高版本(或者 API 21 或更高版本?)。

    【讨论】:

      【解决方案2】:

      ConversationAlertDialog 类中创建一个接口。

      public interface onActionSelect{
      void onOkSelect();
      void onCancelSelect();
      }
      

      在 Activity 上实现它并将它的引用传递给 ConversationAlertDialog 类。然后像这样从对话框中调用。

        // For Positive Button Click
        public void onClick(DialogInterface dialog, int id) {
          // User confirms
          if(mCallBack != null) mCallBack.onOkSelect()
       }
      
        // For Negative  Button Click
        public void onClick(DialogInterface dialog, int id) {
          // User confirms
          if(mCallBack != null) mCallBack.onCancelSelect()
       }
      

      当点击正面或负面按钮时,您将在 MainActivity 中收到通知。

      【讨论】:

        【解决方案3】:
        public class ConversationAlertDialog extends DialogFragment {
            private onMyEvent event;
            public void setMyEvent(onMyEvent e)
            {
                this.event=e;
            }
            public static Dialog createDialog(Context context) {
                // Use the Builder class for convenient dialog construction
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
        
                builder.setMessage("Continue?")
                       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // User confirms
                                if(null!=event)
                                {
                                    event.ok();
                                }
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if(null!=event)
                                {
                                    event.cancel();
                                }
                                // User cancelled
                            }
                        });
                // Create the AlertDialog object and return it
                return builder.create();
            }
            public interface onMyEvent{
                void ok();
                void cancel();
            }
        }
        
        buttonConvert.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Dialog  dialog=ConversationAlertDialog.createDialog(ConversionActivity.this);
                dialog.setMyEvent(new onMyEvent{....})
                dialog.show();
            }
        });
        

        【讨论】: