【问题标题】:android google map supportmap fragment can't be initialized in fragmentandroid google map supportmap片段无法在片段中初始化
【发布时间】:2020-11-26 07:08:12
【问题描述】:

我正在尝试使用片段在 android 中创建实现 Google-Map:

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_map_test, container, false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //the line below get's error
        val mapFragment = view?.findViewById<View>(R.id.sp_map_test) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

我的 XML :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapTestFragment">


    <fragment
        android:id="@+id/sp_map_test"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


</LinearLayout>

但它找不到 SupportMap 片段。我该如何解决这个问题?

我也试过这个 - val mapFragment = parentFragmentManager.findFragmentById(R.id.sp_map_test) as SupportMapFragment

null 不能转换为非 null 类型 com.google.android.gms.maps.SupportMapFragment

【问题讨论】:

    标签: android google-maps kotlin android-fragments


    【解决方案1】:

    插入

    val mapFragment = view?.findViewById<View>(R.id.sp_map_test) as SupportMapFragment
    

    val mapFragment = parentFragmentManager.findFragmentById(R.id.sp_map_test) as SupportMapFragment
    

    使用

    val mapFragment = supportFragmentManager
                .findFragmentById(R.id.map) as SupportMapFragment
    

    参考MapFragment Referance

    【讨论】:

      【解决方案2】:

      你必须把它放在onCreateView中

      override fun onCreateView(
                  inflater: LayoutInflater, container: ViewGroup?,
                  savedInstanceState: Bundle?
          ): View? {
              val view = inflater.inflate(R.layout.fragment_map_test, container, false)
              val mapFragment = view?.findViewById<View>(R.id.sp_map_test) as SupportMapFragment
              mapFragment.getMapAsync(this)
          }
      

      或者您也可以从模板创建支持地图片段

      在 Android Studio 中选择 New -> Fragment -> Google Map Fragment

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-16
        • 1970-01-01
        • 1970-01-01
        • 2021-04-13
        • 2020-12-26
        • 1970-01-01
        • 1970-01-01
        • 2013-07-18
        相关资源
        最近更新 更多