在 android studio 中,我创建了一张地图,上面有数百个标记。我想将它们分成单独的类并将它们放在一个单独的包中,这样我的主代码中就没有大量的标记列表。有没有办法做到这一点?我正在使用 Kotlin。
lanybo 回答:如何将地图标记添加到单独的类文件?
所以我认为你想说的是。 有一个活动,比如说 MainActivity,它有地图,上面有大约 200 个标记。
并且所有这些都是单独初始化和分配的,您希望将它们全部放在一起,以便您只需搜索一个即可使用它们。
如果是这样,我的建议是。
创建一个单独的数据类来存储标记和其他相关数据。
data class MarkerInfo(
//marker ID
val id:Int,//marker Data
val markerData:Marker,//other Data
var otherData:String
)
现在开始存储和访问数据。
class MainActivity(){
//at the top level,inside Activity
// This will create an empty list of Marker Info
var markerData = mutableListOf<MarkerInfo>()
//Now take any function,let's say x
private fun x(){
//Mark a Marker on Map and assign it to a variable.
val markerA : Marker = map.addMarker( MarkerOptions.position(somePosition))
//we assign a function with id and other relevant data
val x= markerData.size
//store data in list
markerData.add(MarkerInfo(x,markerA,"This is a very useful marker"))
}
}
//now to access that marker.
//let's say there is a function named y.
private fun y(){
//say we want to access the first marker
//there are two ways to do so.
//first method: you know some data which is already in there let's say we know id
for(i in markerData){
if(i.id == 1){
Log.d("TAG",i.toString())
}
}
//second method: directly
Log.d("TAG",markerData[0].toString())
}