【问题标题】:Is there a way to get a Class Item (with custom Adapter) from long-clicked ListViewItem有没有办法从长按 ListViewItem 获取类项(使用自定义适配器)
【发布时间】:2019-11-13 15:35:26
【问题描述】:

我已经: 一类

class Cars (Val Name String, Val Type String, Val Year String)

可变列表

var listeCars : MutableList<Cars>? = null

带有编辑和删除菜单项的菜单 带有自定义适配器的列表视图 此列表视图已注册为上下文菜单

registerForContextMenu(listView)

override fun onContextItemSelected(item: MenuItem): Boolean {
        val info = item.menuInfo as AdapterContextMenuInfo
        val carx = listeConsultations!![info.position]

// 最后一行不起作用,即使我使用它来代替

val carx = listView.adapter.getItem(info.position) as Car

// 因为我想检索 Car 类项来用它做一些这样的操作,

        return when {
            item.itemId == R.id.menuDelete -> {
                deleteCar(carx)
                true
            }
            item.itemId == R.id.menuEdit -> {
                updateCar(carx)
                true
            }
            else -> super.onContextItemSelected(item)
        }
    }

private fun updateCar(carx: Car?) {
    val builder = AlertDialog.Builder(applicationContext)
    builder.setTitle("Edit Car")
    val inflater = LayoutInflater.from(applicationContext)
    val view = inflater.inflate(R.layout.edit_car,null)
// .....
}

private fun updateCar(carx: Car?) {
// .....
}

【问题讨论】:

  • 为什么这两行不工作,确切地说?你有错误吗?如果有,它们是什么?

标签: android kotlin android-listview


【解决方案1】:
override fun onContextItemSelected(item: MenuItem): Boolean {

   when(item){

      is Cars -> {

          //item is Cars Type in this brace
      }
   }

 ...
}

希望这会有所帮助。

【讨论】:

  • 不,它没有帮助,编译器给出了这个错误信息 Incompatible types: Cars and MenuItem !感谢您的尝试!
  • @MohamedBenattou 为什么你通过MenuItem而不是通过Cars
  • 来自 Google : override fun onContextItemSelected(item: MenuItem): Boolean { val info = item.menuInfo as AdapterView.AdapterContextMenuInfo return when (item.itemId) { R.id.edit -&gt; { editNote(info.id) true } R.id.delete -&gt; { deleteNote(info.id) true } else -&gt; super.onContextItemSelected(item) } } @huange 12345
猜你喜欢
  • 1970-01-01
  • 2015-07-09
  • 2020-04-16
  • 2012-04-24
  • 1970-01-01
  • 2023-01-26
  • 1970-01-01
  • 2015-11-15
  • 2012-02-15
相关资源
最近更新 更多