android – 是否可以将MapView与FragmentManager和ListFragment一起使用

我的应用程序在左侧使用ListFragment,用户可以使用它来选择右侧使用的片段.

在排序中,似乎不可能多次显示MapView.第一个问题是它只允许每个Activity有一个MapView实例.

# Exception 1:
You are only allowed to have a single MapView in a MapActivity

因此,我将我的MapView和容器保存在Activity类中:

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   FragmentManager.enableDebugLogging(true);
   setContentView(R.layout.main);
   mapViewContainer = LayoutInflater.from(this).inflate(R.layout.maplayout,null);
   mapView = (MapView) mapViewContainer.findViewById(R.id.map_view); 
}

但是,这给了我下一个问题:

# Exception 2:
The specified child already has a parent. 
You must call removeView() on the child’s parent first.

我试图删除视图,使用此代码

((ViewGroup)mapViewContainer).removeView(mapView);
((ViewGroup)mapView.getParent()).removeView(mapView);

得到了NullPointerExeption.

我会很感激任何好的想法,或者如果你能成功做到这一点,你会分享吗?

谢谢 :)

解决方法

是的,也碰到了这个.

不要在片段的XML布局文件添加MapView.相反,只需在具有id =“@ id / your_map_container_id”的LinearLayout中留下一个位置即可.

在YourMapContainerFragment中声明一个MapView私有成员:

public class YourMapContainerFragment extends Fragment {
    private MapView mMapView;
    //...

然后,在YourMapContainerFragment的onCreateView()中这样做:

public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
    // ... Inflate your fragment's layout...
    // ...
    if (mMapView == null) {
        mMapView = new MapView(getActivity(),/*String*/YOUR_MAPS_API_KEY);
    } else {
        ((ViewGroup)mMapView.getParent()).removeView(mMapView);
    }
    ViewGroup mapContainer = (ViewGroup) fragmentLayout.findViewById(R.id.your_map_container_id);
    mapContainer.addView(mMapView);
    // ...
}

这将使相同的MapView对象在片段的删除/添加中重复用于活动.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...