我在getEventId类中有一个称为DataAdapter的方法,但是我无法从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
     }
  }
  .....
}

10-08 14:53