gpt4 book ai didi

android - Kotlin - 无法访问另一个类中的方法

转载 作者:行者123 更新时间:2023-12-02 13:07:49 25 4
gpt4 key购买 nike

我在 DataAdapter 类中有一个名为 getEventId 的方法,但我无法从我的 MainActivity 类访问它,并且不确定为什么?

数据适配器

class DataAdapter (events: ArrayList<Array<String>>) : RecyclerView.Adapter<DataAdapter.ViewHolder>() {

private val TAG = "Adapter"

private val events = events

inner class ViewHolder (view: View) : RecyclerView.ViewHolder(view) {
var id = ""
val title: TextView = view.txtTitle
val date: TextView = view.txtDate
}

fun getEventId (position: Int): Int? {
return if (events.isNotEmpty()) events[position][0].toInt() else null
}

.....
}

主要 Activity

class MainActivity : AppCompatActivity(), RecyclerItemClickListener.OnRecyclerClickListener {

private val eventsDatabase: DatabaseHelper = DatabaseHelper(this)
private var events = ArrayList<Array<String>>()

...

override fun onItemClick(view: View, position: Int) {
var itemId = DataAdapter.getEventId(position)

Toast.makeText(this, "Normal tap on id: $itemId", Toast.LENGTH_SHORT).show()
}

...
}

最佳答案

您需要在类的实例上而不是在类本身上调用 getEventId(position)

class MainActivity : AppCompatActivity(), RecyclerItemClickListener.OnRecyclerClickListener {

private val eventsDatabase: DatabaseHelper = DatabaseHelper(this)
private var events = ArrayList<Array<String>>()
private var adapter = DataAdapter(arrayListOf<Array<String>>())

...

override fun onItemClick(view: View, position: Int) {
var itemId = adapter.getEventId(position)

Toast.makeText(this, "Normal tap on id: $itemId", Toast.LENGTH_SHORT).show()
}

...
}

如果您需要调用 getEventId(position) 而不实例化您的类(我怀疑这里可能是这种情况),则需要将其添加到伴生对象中。

class DataAdapter (events: ArrayList<Array<String>>) : RecyclerView.Adapter<DataAdapter.ViewHolder>() {

private val TAG = "Adapter"

private val events = events

inner class ViewHolder (view: View) : RecyclerView.ViewHolder(view) {
var id = ""
val title: TextView = view.txtTitle
val date: TextView = view.txtDate
}



companion object{
fun getEventId (position: Int): Int? {
return if (events.isNotEmpty()) events[position][0].toInt() else null
}
}
.....
}

关于android - Kotlin - 无法访问另一个类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59021644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com