[英]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.一旦我的应用程序第一次打开,就会出现一个对话框片段(在MainActivity
中),解释为什么需要一些权限,最后有一个接受按钮。 I have set an onClick listener to this button, where I want to show the default popup to ask for the permissions.我已经为此按钮设置了一个 onClick 侦听器,我想在其中显示默认弹出窗口以请求权限。 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.为此,我需要ActivityCompat.requestPermission()
function,它需要应该在其中打开的活动。我尝试了几种方法,例如MainActivity()
或this@MainActivity
或this@WelcomeDialogFragment
等,但这些都没有工作了。
Is there a way to do that?有没有办法做到这一点? (Right after the button is pressed, the dialog is closed.) This is my WelcomeDialogFragment class: (按下按钮后,对话框立即关闭。)这是我的 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.谢谢。
You can use getActivity()
or requireActivity()
, as in:您可以使用getActivity()
或requireActivity()
,如:
ActivityCompat.requestPermissions(requireActivity(), list_of_permissions)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.