2016-07-15 133 views
4

我对Google Maps有问题,例如getSupportFragmentManager()。findFragmentById返回始终为空。你有一个想法如何解决这个问题?getSupportFragmentManager()。findFragmentById在Android中的fragment中返回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> 

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); 
... 

我在活动谷歌地图,并将其与代码工作:

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 

我想在片段中重新使用它,因为我需要片段中的地图,而不是活动中的地图,但它不起作用。

我想:

  • 调用此代码 “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); 和类似的变化,但在任何情况下,我得到null为mapFragment。

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

+0

你必须使用'onCreateView'的片段。你能在这里发布日志,以便我们知道错误是什么? –

+0

如果我使用'onCreateView',我仍然得到这个错误。您可以在我的问题更新 –

+0

中看到错误报告,我找到了解决方案。谢谢:) –

回答

9

问题是你试图使用Activity的FragmentManager,你应该使用Fragment的子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; 
} 
+0

Tnx的回复,但这个代码也没有工作。 'findFragmentById'仍然返回null。 –

+1

我很抱歉,这是我的错,但它工作!非常感谢你! :) –

+0

完成。 Tnx再次:) –

相关问题