如何在SupportMapFragment中使用View binding?

7
如何在SupportMapFragment中使用View绑定?参考我的代码。
我在布局中有一个地图片段,我想在片段中使用视图绑定。
代码如下:
``` val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment ```
请提供解决方案。
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.SupportMapFragment
import com.zeddigital.zigmaster.R
import com.zeddigital.zigmaster.databinding.FragmentHomeBinding

class HomeFragment : Fragment() {
    private lateinit var mMap: GoogleMap

    private var binding : FragmentHomeBinding ?=null
    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View {
        binding = FragmentHomeBinding.inflate(inflater)

        // binding.myTextView.text = "sample"

        val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync { googleMap ->

        }

        return binding!!.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding=null
    }
}





<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".ui.home.HomeFragment">

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

</androidx.coordinatorlayout.widget.CoordinatorLayout>
2个回答

11

上述答案是正确的,但对于最新的Android Studio,我会发布一些代码更改。

从现在开始,建议使用<androidx.fragment.app.FragmentContainerView />代替<fragment />

现在可以如下使用视图绑定:

对于Java:

SupportMapFragment mapFragment = (SupportMapFragment) childFragmentManager.findFragmentById(binding.map.getId());

对于Kotlin:

val mapFragment = childFragmentManager.findFragmentById(binding.map.id) as SupportMapFragment

9
如果您想像下面引用的悬赏信息中提到的那样,使用视图绑定来处理MapFragment的ID:

如何在SupportMapFragment的ID中使用View绑定?

您可以简单地编写
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment

as

val mapFragment = childFragmentManager.findFragmentById(binding.map.id) as SupportMapFragment

这样可以防止它成为null,这正是您想要的情况。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接