【问题标题】:How do I convert string from shared preferences to MutableList<LatLng> pairs to draw polylines in kotlin?如何将字符串从共享首选项转换为 MutableList<LatLng> 对以在 kotlin 中绘制折线?
【发布时间】:2021-10-13 21:01:13
【问题描述】:

我想将共享首选项中的值转换为 LatLng 对的可变列表以绘制折线。我不知道如何转换它。请帮助。在这里,我将共享首选项polyl 中的值设为 [lat/lng:(10.184133,76.4005395),lat/lng(10.1840907,7​​6.4004505)] 等。如何将其转换为 LatLng 对的可变列表,以便绘制折线。


            val sharedPr= activity?.getPreferences(Context.MODE_PRIVATE)
            val polyl= sharedPr?.getString("polylinep",null)

            Toast.makeText(requireContext() ,"$polyl", Toast.LENGTH_SHORT).show()
            try {
            val polyline10= polyl as MutableList<LatLng>

            Toast.makeText(requireContext() ,"ub$polyline10", Toast.LENGTH_SHORT).show()


            map.addPolyline(
                    PolylineOptions().apply {
                        width(10f)
                        color(Color.BLUE)
                        jointType(JointType.ROUND)
                        startCap(ButtCap())
                        endCap(ButtCap())
                        addAll(polyline10)
                    }

                )


            } catch (e:java.lang.ClassCastException){

            }

【问题讨论】:

    标签: android google-maps kotlin google-polyline polylineoptions


    【解决方案1】:

    序言

    我不知道您如何创建字符串“[lat/lng:(10.184133,76.4005395),lat/lng(10.1840907,7​​6.4004505)]”,但我认为将坐标转换为JSON 字符串,然后将其保存到首选项。如果您无法更改这些坐标在第一时间保存的方式,那么我的回答对您没有帮助。

    解决方案

    保存到共享首选项

    考虑到您在某种列表中拥有坐标并希望将它们保存到首选项中,例如,您可以使用 GSON 之类的库将该列表转换为表示该列表的 JOSN 字符串。 要了解这是如何完成的,请查看本教程:https://www.tutorialspoint.com/how-to-save-arraylist-to-sharedpreferences-on-android

    从共享首选项中读取

    现在坐标列表已保存为 JSON 字符串,您可以从共享首选项中读取它,将其转换回 JSON 对象并从中读取您的列表。例如,此线程的第一个答案中显示了这一点:Is it ok to save a JSON array in SharedPreferences?

    希望能帮到你:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 2019-09-09
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多