【问题标题】:Why my Map fragment return null?为什么我的地图片段返回 null?
【发布时间】:2014-08-13 23:09:12
【问题描述】:

我看过this 和类似的帖子。

在我看来,我所做的一切都是正确的。

还是,

SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);`

返回 NULL。

activty_map.xml

<FrameLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >


<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"
/>

<Button 
android:id="@+id/startgeo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set Geo"
android:background="@android:color/transparent"
android:layout_gravity="right"/>

</FrameLayout>

我的活动中的代码:

    setContentView(R.layout.activty_map);
    SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map); //RETURNS NULL !!!
    map = mapFrag.getMap();

【问题讨论】:

  • 我认为 getMap() 可能返回 null,确定不是吗?
  • 如何添加片段?
  • @nikis 在这种情况下我需要添加片段吗?

标签: android google-maps android-fragments


【解决方案1】:

根据其他一些开发人员的mentioned,谷歌地图需要一些时间才能加载。这就是为什么您需要在延迟(比如说 500 毫秒)后调用地图初始化代码的原因。

例如:

setContentView(R.layout.activty_map);

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map); //should'nt be null after 500ms
        map = mapFrag.getMap();
    }
}, 500);

另外,我建议你依靠onResume方法来确认加载完成。

【讨论】:

  • 调用 onResume() 没有帮助:-((
  • 试试onResumeFragments
  • 这个想法是地图加载需要时间,并且只有在加载完成后才应该启动它的引用。就像我们在android中绑定Services一样——是异步的。
  • 两者都不是,再次为 NULL :-((
  • 您是否尝试使用Handler 增加延迟?粘贴更多代码
【解决方案2】:

您可以确保片段在 onResumeFragments 中可用,而不仅仅是使用任意延迟发布它,#http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html#onResumeFragments()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多