简体   繁体   English

在Kotlin中,访问RecyclerView适配器的内部类中的外部类成员的最佳方法是什么?

[英]What is the best way to access members of outer class in the inner class of RecyclerView adapter in Kotlin?

I'm creating my first Kotlin classes in my Android application. 我正在Android应用程序中创建第一个Kotlin类。 Usually, for logging purposes, I have a constant with the name TAG. 通常,出于记录目的,我有一个名称为TAG的常量。 I defined it in my RecyclerView Adapter as: 我在RecyclerView适配器中将其定义为:

class MyAdapter(private val dataList: ArrayList<MyData>): RecyclerView.Adapter<MyAdapter.ViewHolder>() {

    private val TAG: String? = MyAdapter::class.simpleName
    .
    .
    .

    class ViewHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener {
        fun bindData(){
            //some statements
        }

        override fun onClick(p0: View?) {
           //I want to use the above defined TAG here as I would do in Java:
           // Log.d(TAG, "");
        }
    }
}

I am unable to access the variable TAG in the onClick() 我无法在onClick()中访问变量TAG

您可以将ViewHolder类设置为inner

Use the companion object : 使用companion object

class MyAdapter(private val dataList: ArrayList<String>) :
    RecyclerView.Adapter<MyAdapter.ViewHolder>() {

    class ViewHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener {
        fun bindData() {
            //some statements
        }

        override fun onClick(p0: View?) {
            Log.d(TAG, "")
        }
    }

    companion object {
        val TAG: String? = MyAdapter::class.simpleName
    }

}

You can also put 你也可以放

private val TAG: String? = MyAdapter::class.simpleName

on top level of the file. 在文件的顶层。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从Kotlin的内部类访问外部类的成员? - how to access member of outer class from inner class in Kotlin? 如何从recyclerView适配器访问密封类的内部数据类 - How to access inner data classes of sealed class from a recyclerView adapter Kotlin内部类正在访问外部类? - Kotlin inner class accessing outer class? 如何从Java中的静态内部类访问外部类的私有成员 - How to access private members of outer class from static inner class in Java 如何将 ViewBinding 与 RecyclerView 适配器与 Kotlin 中已经存在的内部 class 一起使用? - How can I use ViewBinding with RecyclerView Adapter with an already existing inner class in Kotlin? Kotlin:内部类如何访问在外部类中声明为参数的变量? - Kotlin: How can an inner class get access to a variable declared as a parameter in an outer class? RecyclerView 适配器类中 Android 视图绑定的正确方法是什么? - What is the right way of Android View Binding in the RecyclerView adapter class? 什么是更好的方法,将适配器保持为活动的内部类别或外部? - What is the better way, keeping adapter as an inner class of activity or outside? OnQueryTextListener,无法访问类成员(RecyclerView或Adapter出现空指针异常) - OnQueryTextListener, can't access class members (null pointer exception with my RecyclerView or my Adapter) 如何在 Kotlin 的内部 class 中使用外部 class 的属性? - How to use a property of a outer class in inner class in Kotlin?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM