【发布时间】:2016-11-19 04:15:59
【问题描述】:
我在使用 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>
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);
...
我在 Activity 中有 Google 地图,它可以使用代码:
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);和类似的变体,但在所有情况下,mapFragment 都为空。
你知道我该如何解决这个问题吗?
【问题讨论】:
-
您必须使用
onCreateView来表示片段。你能把日志贴在这里让我们知道错误是什么吗? -
如果我使用
onCreateView我仍然会收到此错误。您可以在我的问题更新中看到错误报告 -
我找到了解决方案。谢谢:)
标签: android google-maps android-fragments fragment