getSupportFragmentManager().findFragmentById为android中的片段中的谷歌地图返回null?

Vla*_*nic 11 android google-maps fragment android-fragments

我的Google地图有问题,即getSupportFragmentManager().findFragmentById返回null.你知道如何解决这个问题吗?

这是代码:

fragment_map.xml:

<FrameLayout 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="com.myapp.something.MapFragment">
<fragment
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment" />                  
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)

MapsFragment.java:

public class MapFragment extends Fragment implements OnMapReadyCallback, android.location.LocationListener

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    SupportMapFragment mapFragment = (SupportMapFragment) this.getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
...
Run Code Online (Sandbox Code Playgroud)

我在Activity中有Google地图,它可以使用代码:

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
Run Code Online (Sandbox Code Playgroud)

我试图在片段中重用它,因为我需要片段中的映射,而不是活动,但它不起作用.

我试过了:

  • 在"onCreateView"函数中调用此代码
  • SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
  • GoogleMap mGoogleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap(); 已弃用,应用程序崩溃
  • SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map); 和类似的变化,但在所有情况下,我得到mapFragment null.

你知道我怎么能解决这个问题?

Dan*_*ent 20

问题是,你要使用活动的FragmentManager,你应该使用碎片的孩子FragmentManager.

删除onCreate()片段中的覆盖,并onCreateView()在您给布局膨胀的位置添加覆盖并调用getMapAsync():

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_map, container, false);

    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);

    mapFragment.getMapAsync(this);

    return rootView;
}
Run Code Online (Sandbox Code Playgroud)