Skip to content
Advertisement

How to ask for permissions in an onClick event from a button inside a dialog fragment

As soon as my app opens up for the first time, a dialog fragment should come up (in the MainActivity), explaining why some permissions are needed, and there is an Accept button at the end. I have set an onClick listener to this button, where I want to show the default popup to ask for the permissions. To do that, I need the ActivityCompat.requestPermission() function, which requires the activity where it should be opened in. I have tried several things, like MainActivity(), or this@MainActivity or this@WelcomeDialogFragment etc, but none of these worked.

Is there a way to do that? (Right after the button is pressed, the dialog is closed.) This is my WelcomeDialogFragment class:

class WelcomeDialogFragment : DialogFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView : View = inflater.inflate(R.layout.welcome_popup, container, false)

        rootView.accept_btn.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                ActivityCompat.requestPermissions(
                    this@MainActivity, arrayOf(
                        Manifest.permission.ACCESS_BACKGROUND_LOCATION
                    ), PackageManager.PERMISSION_GRANTED)
            }
            ActivityCompat.requestPermissions(
                this@MainActivity, arrayOf(
                    Manifest.permission.SEND_SMS, Manifest.permission.READ_CONTACTS
                ), PackageManager.PERMISSION_GRANTED)
            dismiss()
        }

        return rootView
    }
}

Thank you.

Advertisement

Answer

You can use getActivity() or requireActivity(), as in:

ActivityCompat.requestPermissions(requireActivity(), list_of_permissions)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement