我在使用 Google map 时遇到问题,即 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 map ,它可以使用代码:
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
我试图在 fragment 中重用它,因为我需要 fragment 中的 map ,而不是 Activity 中的 map ,但它不起作用。
我试过:
- 在“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。
你知道我怎样才能解决这个问题吗?
最佳答案
问题是您正在尝试使用 Activity 的 FragmentManager,而您应该使用 Fragment 的子 FragmentManager。
删除 Fragment 中的 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;
}
关于android - getSupportFragmentManager().findFragmentById 为 android fragment 中的谷歌地图返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38404814/