Show dialog from fragment?

前端 未结 7 809
再見小時候
再見小時候 2020-11-30 19:17

I have some fragments that need to show a regular dialog. On these dialogs the user can choose a yes/no answer, and then the fragment should behave accordingly.

Now,

7条回答
  •  渐次进展
    2020-11-30 20:10

    Here is a full example of a yes/no DialogFragment:

    The class:

    public class SomeDialog extends DialogFragment {
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            return new AlertDialog.Builder(getActivity())
                .setTitle("Title")
                .setMessage("Sure you wanna do this!")
                .setNegativeButton(android.R.string.no, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // do nothing (will close dialog)
                    }
                })
                .setPositiveButton(android.R.string.yes,  new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // do something
                    }
                })
                .create();
        }
    }
    

    To start dialog:

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            // Create and show the dialog.
            SomeDialog newFragment = new SomeDialog ();
            newFragment.show(ft, "dialog");
    

    You could also let the class implement onClickListener and use that instead of embedded listeners.

    Callback to Activity

    If you want to implement callback this is how it is done In your activity:

    YourActivity extends Activity implements OnFragmentClickListener
    

    and

    @Override
    public void onFragmentClick(int action, Object object) {
        switch(action) {
            case SOME_ACTION:
            //Do your action here
            break;
        }
    }
    

    The callback class:

    public interface OnFragmentClickListener {
        public void onFragmentClick(int action, Object object);
    }
    

    Then to perform a callback from a fragment you need to make sure the listener is attached like this:

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentClickListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement listeners!");
        }
    }
    

    And a callback is performed like this:

    mListener.onFragmentClick(SOME_ACTION, null); // null or some important object as second parameter.
    

提交回复
热议问题