android Фрагмент карты поддержки карты Google не может быть инициализирован во фрагменте - PullRequest
0 голосов
/ 06 августа 2020

Я пытаюсь создать реализацию Google-Map в android с использованием фрагмента:

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)
    }

My 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 нельзя преобразовать в ненулевой тип com.google. android .gms.maps .SupportMapFragment

Ответы [ 2 ]

1 голос
/ 06 августа 2020

Содержит

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

Ссылку Ссылку на фрагмент карты

0 голосов
/ 06 августа 2020

Вы должны поместить его в 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

...