简体   繁体   中英

How do I communicate between alert dialog back to my fragment?

I have a class called AlertDialogFragment that will be used to create an alert dialog when needed throughout my program. The fragment that creates the dialog will call a function if the positive button is clicked or nothing if the negative button is clicked. Im fairly new to android development and any tips or help is appreciated.

Here is my AlertDialogFragment:

class AlertDialogFragment : DialogFragment() {


    companion object {
        private val TAG = "AlertDialogFragment"


        fun newInstance(message: String, positiveBtnText: String, negativeBtnText: String): AlertDialogFragment {
            val fragment = AlertDialogFragment()
            fragment.isCancelable = false

            val args = Bundle()
            args.putString("aMessage", message)
            args.putString("aPositiveBtnText", positiveBtnText)
            args.putString("aNegativeBtnText", negativeBtnText)

            fragment.arguments = args
            return fragment
        }


    }


    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        Log.d(TAG, "onCreateDialog called")
        super.onCreateDialog(savedInstanceState)
        return activity?.let {
            val builder = AlertDialog.Builder(it)
            builder.setMessage(arguments?.getString("aMessage"))
                    .setPositiveButton(arguments?.getString("aPositiveBtnText"), DialogInterface.OnClickListener { dialog, id ->
                        Log.d(TAG, "Yes!")
                    })
                    .setNegativeButton(arguments?.getString("aNegativeBtnText"), DialogInterface.OnClickListener { dialog, id ->
                        Log.d(TAG, "Dismiss!")
                    })

            Log.d(TAG, "onCreateDialog ending")
            builder.create()
        } ?: throw IllegalStateException("Activity can not be null")
    }


} 

Here is my attempt to initialize the alert dialog and set the target fragment:

try {
            AlertDialogFragment alertDialogFragment = new AlertDialogFragment().Companion.newInstance(
                    "Would you like to continue?",
                    "Yes",
                    "Dismiss");
            alertDialogFragment.setTargetFragment(this, TARGET_FRAGMENT_REQUEST_CODE);
            alertDialogFragment.show(getActivity().getSupportFragmentManager(), "dialog");
        }catch (Exception e){
            e.printStackTrace();
        }

Thanks in advance for any help!

EDIT: I am using kotlin for the alert dialog and the fragment that initializes it, is in java.

You can retrieve the target fragment and request code you passed in and then use that to call onActivityResult :

targetFragment?.let { fragment ->
    fragment.onActivityResult(fragment.targetRequestCode, Activity.RESULT_OK, null)
}

and in your function:

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        Log.d(TAG, "onCreateDialog called")
        super.onCreateDialog(savedInstanceState)
        return activity?.let {
            val builder = AlertDialog.Builder(it)
            builder.setMessage(arguments?.getString("aMessage"))
                    .setPositiveButton(arguments?.getString("aPositiveBtnText"), DialogInterface.OnClickListener { dialog, id ->
                        Log.d(TAG, "Yes!")
                        targetFragment?.let { fragment ->
                            fragment.onActivityResult(fragment.targetRequestCode, Activity.RESULT_OK, null)
                        }
                    })
                    .setNegativeButton(arguments?.getString("aNegativeBtnText"), DialogInterface.OnClickListener { dialog, id ->
                        Log.d(TAG, "Dismiss!")
                    })

            Log.d(TAG, "onCreateDialog ending")
            builder.create()
        } ?: throw IllegalStateException("Activity can not be null")
    }

In your launching fragment you override onActivityResult and handle the returned value.

Note that if your fragment is recreated, you will have to re-assign the target fragment.

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