Android Google Maps API v2:FragmentManager.findFragmentById() 始终返回 NULL

问题描述 投票:0回答:1

在开发涉及Android Google Maps API v2.0的应用程序时,我发现

FragmentManager.findFragmentById(<resource ID of fragment XML file>)
总是返回NULL。我从 XML 文件中扩充了该片段。我可以毫无问题地获取视图,但是片段本身呢?我什至尝试了 4 秒的延迟,以确保在我获取 ID 时所有内容都已加载。

//
// res/layout/mapfragment.xml:
//

<?xml version="1.0" encoding="UTF-8"?>
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/map"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              class="com.google.android.gms.maps.SupportMapFragment"/>

// Transmitting resource ID of fragment in XML

    ui.setMapFragmentResourceID(R.layout.mapfragment);

..

// Showing map

    @Override
        public void showMap() {

    ...

        m_map = m_currentActivity.getLayoutInflater().inflate(m_mapFragmentResourceID, null);

        cv.postDelayed(new Runnable() {
            @Override
            public void run() {
                afterShowMapView();
            }
        }, 4000);
    }

// 4000 msec delay to allow for everything to load

    public void afterShowMapView()
    {
        FragmentActivity fa = (FragmentActivity)m_currentActivity;

        FragmentManager fm = fa.getSupportFragmentManager();
        SupportMapFragment f = (SupportMapFragment)fm.findFragmentById(m_mapFragmentResourceID);
    }

//
// f is always null
//

如何获取 Fragment/SupportFragment 对象本身(而不是通过膨胀布局获得的视图)?

android android-fragments maps
1个回答
2
投票

您使用了正确的 ID,即基于您的 XML 的

R.id.map
。如果我正确理解您的代码,那么您正在使用
R.layout.mapfragment

© www.soinside.com 2019 - 2024. All rights reserved.