Kotlin中如何获取列表选中项索引?现有代码返回首索引问题
解决Google Map选中地点对应索引获取问题
我们从Google Places API获取地点列表并在Google Map上标记展示,用户选择地点传入showInfoWindow函数后,当前逻辑始终返回列表首个索引,无法正确获取选中地点的对应索引,问题及解决方案如下:
问题原因分析
核心问题出在Place对象的匹配逻辑上:
- 若未给
Place类正确重写equals()和hashCode(),直接用==比较对象时,会默认比较引用地址而非地点的唯一标识(如placeId),导致无法匹配到正确的标记 - 当前代码未关联原地点列表,没有显式获取索引的逻辑
解决方案
1. 改用地点唯一标识匹配(推荐)
Google Places返回的placeId是每个地点的唯一标识,直接用它来做匹配判断,比重写equals更直接可靠:
private fun showInfoWindow(place: Place, placesList: List<Place>) { // 获取选中地点在原列表中的索引 val selectedIndex = placesList.indexOfFirst { it.placeId == place.placeId } if (selectedIndex != -1) { // 此处可使用selectedIndex执行后续逻辑 // 例如:Log.d("SelectedIndex", selectedIndex.toString()) } // AR窗口展示逻辑(改用placeId匹配) val matchingPlaceNode = anchorNode?.children?.filter { it is PlaceNode }?.first { val otherPlace = (it as PlaceNode).place ?: return@first false otherPlace.placeId == place.placeId } as? PlaceNode matchingPlaceNode?.showInfoWindow() // Map标记窗口展示逻辑(改用placeId匹配) val matchingMarker = markers.firstOrNull { val placeTag = (it.tag as? Place) ?: return@firstOrNull false placeTag.placeId == place.placeId } matchingMarker?.showInfoWindow() }
2. 重写Place类的equals方法(备选)
如果希望保留==比较的写法,需在Place类中基于placeId重写equals()和hashCode():
data class Place( val placeId: String, // 其他字段:名称、坐标等 ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Place return placeId == other.placeId } override fun hashCode(): Int { return placeId.hashCode() } }
之后即可通过placesList.indexOf(place)获取选中地点的索引,原有匹配逻辑也能正常工作。
内容的提问来源于stack exchange,提问作者kasunk
相关产品推荐
相关产品推荐

