gpt4 book ai didi

android - SupportMapFragment 的 getMap() 返回 null

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:03:36 26 4
gpt4 key购买 nike

我正在尝试动态创建一个 SupportMapFragment 并将其放入 FrameLayout 容器中。

我的问题是 mMapFragment.getMap() 返回 null...

有人可以帮忙吗?

CenterMapFragment.java

public class CenterMapFragment extends Fragment {

private SupportMapFragment mMapFragment;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

return inflater.inflate(R.layout.center_map_fragment, container, false);
}

@Override
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);

if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()) == ConnectionResult.SUCCESS) {
setUpMapIfNeeded();
}
}


private void setUpMapIfNeeded() {

if (mMapFragment == null) {

mMapFragment = SupportMapFragment.newInstance();
FragmentTransaction fragmentTransaction =
getChildFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.map, mMapFragment);
fragmentTransaction.commit();

setUpMap();
}
}

private void setUpMap() {

GoogleMap map = mMapFragment.getMap();

// map is null!

}

@Override
public void onResume()
{
super.onResume();
setUpMapIfNeeded();
}
}

center_map_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<FrameLayout
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>

<Button
android:id="@+id/btn_loc"
android:layout_width="60dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="@drawable/locbtn" />

</RelativeLayout>

最佳答案

FragmentTransaction 上的

commit() 不会立即执行其操作。当您调用 setUpMap() 时,onCreateView() 不会在 SupportMapFragment 上被调用,因此还不是 map 。

一种方法是不使用嵌套 fragment ,而是选择让 CenterMapFragment 扩展 SupportMapFragment,在这种情况下 getMap() 应该可以工作onCreateView() 之后的时间(例如,onActivityCreated())。

关于android - SupportMapFragment 的 getMap() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16322017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com