【问题标题】:Android Kotlin - Asking Permission in RecyclerView AdapterAndroid Kotlin - 在 RecyclerView 适配器中询问权限
【发布时间】:2020-07-08 03:30:30
【问题描述】:

这是 Recyclerview 适配器内的代码:

fun DownloadImage(ImageUrl: String?) {
    if (ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.READ_EXTERNAL_STORAGE
        ) != PackageManager.PERMISSION_GRANTED &&
        ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        ActivityCompat.requestPermissions(
            context, // HERE
            arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
            123
        )
        ActivityCompat.requestPermissions(
            context, // AND HERE
            arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
            123
        )
        Functions(context).showToats(context,"Need Permission to access storage for Downloading Image")
    } else {
        Functions(context).showToats(context,"Downloading Image...")
        //Asynctask to create a thread to downlaod image in the background

        DownloadsImage(context).execute(ImageUrl)
    }
}

我收到错误消息:Type mismatch: inferred type is Context but Activity was expected 我已对其进行了评论。

如何正确地做到这一点?

getActivity() 也不起作用。

【问题讨论】:

    标签: android kotlin android-permissions android-context


    【解决方案1】:

    方法getActivity() 将不起作用,因为Recyclerview.Adapter 不是fragment。 要获取对当前activity 的引用,请尝试将其传递给adapter 的构造函数。

    例如,(在 kotlin 中)

    class YourAdapter(val yourActivity : AppCompatActivity) : RecyclerView.Adapter<YourViewHolder>()
    

    然后把它当作

    ActivityCompat.requestPermissions(
                yourActivity, // HERE
                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                123
            )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      相关资源
      最近更新 更多