简体   繁体   中英

Am I doing it correctly?

I'm learning and remembering Android and I want to understand my mistakes. This is my confirm/cancel AlertDialog class. Created it in separate class to split code and not put everything in one 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();
    }
}

This is my Activity where I show AlertDialog:

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

Next I want to create callback so I could write Dialog cancel/confirm behaviour in Activity. This way it will be also easier to use code that is already written in Activity. I am still learning about callbacks so not sure, but I think I should implement interface.

All kind of tips would help me.

Create an Interface in ConversationAlertDialog class.

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

Implement it on Activity and pass it's reference to ConversationAlertDialog class. Then call from dialog like that.

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

You will be notified in MainActivity when positive or negative button is clicked.

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

He is the code I use. I find it quite flexible because you can create several similar dialogs for slightly different tasks. You will need to create a layout file - this gives you a great deal of flexibility on function and style.

My layout file is fragment_ok_cancel_dialog .

In the Activity that calls the dialog you will need to implement the Listener.

implements OkCancelDialogFragment.OkCancelDialogListener

Another advantage is with my code you can change the title and the message to fit the needs of any Activity.

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

Now you need to implement the dialog callback in the Activity that calls the DialogFragment.

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

Now the code for the 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);
    }

}

Please note that .setTitle(title) is valid for API 23 or higher (or maybe API 21 or higher?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM