android-fragments 重新导航时支持MapFragment onDestroy处理

a2mppw5e  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(134)

目前正在使用SupportMapFragment创建我的应用程序的子屏幕:

<?xml version="1.0" encoding="utf-8"?>

    <LinearLayout
   
        <fragment
          android:id="@+id/map"
          android:name="com.google.android.gms.maps.SupportMapFragment"
          tools:context=".MainActivity" />

       <Button
          android:id="@+id/back"
          android:layout_width="wrap_content"

          android:text="@string/back"
       />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

在主屏幕上,我使用MainActivity中的一个按钮调用更改视图函数:

fun loadMapView(view: View) {
    mapFragmentManager= supportFragmentManager;
    
    // First navigation
    if (mapFragment==null){
        val mapFragment = SupportMapFragment.newInstance()
        mapFragmentManager
        .beginTransaction()
        .replace(R.id.map, mapFragment!!)
        .commit()

        mapFragment!!.getMapAsync(this);
    }
    // Second, Third, ... Navigation
    else {
            mapFragmentManager
                .beginTransaction()
                .attach(mapFragment!!)
                .commit()
        }

        setContentView(R.layout.mapView) // Throwing Error when navigating second time
        
        // Setup Backbutton
        val back = findViewById<Button>(R.id.back)
        back.setOnClickListener {
            // Remove Mapfragment (also tried detach)
            mapFragmentManager.beginTransaction().remove(mapFragment!!).commit()

        // Navigate to main screen
        setActivityMain()
    }

第一次导航完全可以正常工作,但第二次导航setContentView会抛出:

Duplicate id 0x7f080180, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.SupportMapFragment
vjhs03f7

vjhs03f71#

我自己解决了这个问题,将XML标记更改为:

<FrameLayout
        android:id="@+id/map"

        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.95"
     />

如果不检查空值,它就可以正常工作:

mapFragment = SupportMapFragment.newInstance()
 mapFragmentManager
        .beginTransaction()
        .replace(R.id.map, mapFragment!!)
        .commit()

 mapFragment!!.getMapAsync(this);

并且按钮监听器还包括:

mapFragmentManager.beginTransaction().remove(mapFragment!!).commit()

相关问题