Java 如何在一个片段中实现GoogleMaps并使用GoogleMap对象?
如何在片段中实现GoogleMap 我正在尝试开发相同的东西,但是无法执行getMap(),因为SupportMapFragment(在执行行(SupportMapFragment)getActivity()时)是getActivity().getSupportFragmentManager().findFragmentById(R.id.map)返回空对象 我尝试过扩展MapFragment和SupportMapFragment而不是Fragment,但它们不起作用 我只是不想创建一个新的活动来显示地图:我只想显示一个地图,而不是我的主要活动。我能实现我的目标吗 我有一个扩展ActionBarActivity的主活动,它替换容器中的片段(取决于用户在抽屉上的选择,X或Y片段被替换并显示)。我拥有两个正在工作的片段,但我无法实现在片段中操纵GoogleMap对象的目标 这是我的mapa.xmlJava 如何在一个片段中实现GoogleMaps并使用GoogleMap对象?,java,android,google-maps,android-fragments,google-maps-android-api-2,Java,Android,Google Maps,Android Fragments,Google Maps Android Api 2,如何在片段中实现GoogleMap 我正在尝试开发相同的东西,但是无法执行getMap(),因为SupportMapFragment(在执行行(SupportMapFragment)getActivity()时)是getActivity().getSupportFragmentManager().findFragmentById(R.id.map)返回空对象 我尝试过扩展MapFragment和SupportMapFragment而不是Fragment,但它们不起作用 我只是不想创建一个新的
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mapaPrincipal"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
高亮显示的行无效,因为SupportMapFragment对象为null,因此getMap()崩溃
需要帮忙吗?提前谢谢
我的问题的解决方案
对于任何面临我这样问题的人:您不应该使用getSupportFragmentManager(),而应该使用getChildFragmentManager()。这一点应保持不变:
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.mapa, container, false);
setupMapIfNeeded();
return rootView;
}
private void setupMapIfNeeded() {
if( mMapa == null ){
SupportMapFragment smf = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapaPrincipal);
if( smf != null ){
Toast.makeText(getActivity(), "Let's go!!", Toast.LENGTH_SHORT).show();
mMapa = smf.getMap();
}else{
Toast.makeText(getActivity(), "SMF is null...", Toast.LENGTH_SHORT).show();
}
if( mMapa != null ){
setupMap();
}
}
}
private void setupMap() {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Configure the map", Toast.LENGTH_SHORT).show();
}
嗨,你可以参考我的答案 你需要这样打电话
SupportMapFragment fragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapaPrincipal);
mMapa = fragment.getMap();
检查:你为什么不使用childFragmentManager?@因此你真的救了我的命!!
SupportMapFragment fragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapaPrincipal);
mMapa = fragment.getMap();