Android:如何制作具有稳定ID的适配器?

gio*_*ine 13 android listview adapter

我已经从BaseAdapter扩展了我自己的自定义适配器以显示listview等等......

我希望它支持单选和多选,所以它必须有稳定的ID.我已经检查过ADAPTER.hasStableIds(),结果是假的.

我已经克服了这种方法,试图在没有运气的情况下获得稳定的id.

public long getItemId(int position) {
   return (long) getItem(position).hashCode();
}
Run Code Online (Sandbox Code Playgroud)

知道怎么做吗?谢谢!

rui*_*ujo 20

覆盖hasStableIds以返回true.

此外,适配器上的数据必须覆盖hashCode()或具有某种类型的id字段才能返回getItemId.

  • hashCodes不是唯一的,默认实现使用position作为id.hashCode如何与项标识符相关? (6认同)
  • 现在是最后的.所以不能再覆盖它了.必须调用setHasStablesIds (3认同)

Muh*_*kal 5

将其添加到您的适配器中:

init {    
    setHasStableIds(true)
}

override fun getItemId(position: Int): Long = position.toLong()
Run Code Online (Sandbox Code Playgroud)