首页 > 解决方案 > 带有 MapView 的片段很慢

问题描述

我正在制作一个应用程序,其中包含一个活动,其中有关抽屉等的所有操作都是handeld,以及显示主要内容的三个片段。在 MainActivity 中,带有地图的片段被放置在片段容器中。但是当我启动应用程序时,在显示地图之前,屏幕会持续 2-3 秒为白色。

我已经尝试使用带有 OnMapReadyCallback 的 getMapAsync,但它不起作用,并且我已经搜索了其他解决方案,但找不到任何有效的解决方案。

MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main_activity)
    setSupportActionBar(toolbar)
    supportActionBar?.title = getString(R.string.app_name)

    val toggle = ActionBarDrawerToggle(
        this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close
    )
    drawer_layout.addDrawerListener(toggle)
    toggle.syncState()
    nav_view.setNavigationItemSelectedListener(this)

    supportFragmentManager.beginTransaction()
        .replace(R.id.fragmentContainer, MapFragment())
        .commit()

    if (!checkDataConnection()) {
        val dialogView = View.inflate(this, R.layout.dialog_no_data, null)
        val dialogBuilder = AlertDialog.Builder(this)
            .setView(dialogView)
            .setCancelable(false)
        val alertDialog = dialogBuilder.show()

        dialogView.rescanDataConnection.setOnClickListener {
            if (checkDataConnection()) {
                alertDialog.dismiss()
            }
        }
    }
}

MapFragment.kt

class MapFragment : Fragment(), OnMapReadyCallback {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_map, container, false)

        val mapView = view.findViewById<MapView>(R.id.mapView)
        mapView.onCreate(savedInstanceState)
        mapView.getMapAsync(this)

        try {
            MapsInitializer.initialize(this.activity)
        } catch (e: GooglePlayServicesNotAvailableException) {
            e.printStackTrace()
        }
        return view
    }

    override fun onMapReady(p0: GoogleMap?) {
        // Necessary function for loading map async
    }
}

那么有人可以帮助我提高性能吗?

标签: androidperformancekotlinandroid-mapview

解决方案


推荐阅读