Android Kotlin - 在 RecyclerView 适配器中请求权限

Android Kotlin - Asking Permission in RecyclerView Adapter

这是 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() 也不起作用。

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

的构造函数

例如,(在科特林中)

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

然后用作

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