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

标签 android google-maps android-fragments fragment

我在使用 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/

相关文章:

android - CSS 中是否有相当于 "max-height"和 "max-width"的属性来按比例缩放图像?

android - Android项目的依赖管理

android - 如何将 Activity 转换为 Fragment?

android - 如何在重新创建 Activity 时跟踪 ViewPager 的选定 fragment (例如旋转)

java - 将数据从在线 MySQL 数据库加载到 Android 应用程序

java - 如何在 fragment 上显示操作栏图标?

android - 链接到自定义谷歌地图

android - 如何获得两个位置之间的行驶距离?

google-maps - 实时谷歌地图

android - 我的应用应该在多大程度上使用 fragment ?