Mapview osmdroid在片段中不可见

时间:2012-12-20 17:43:56

标签: android fragment osmdroid

我试图在Fragment的onActivityCreated中的relativeLayout中添加MapView(org.osmdroid.views.MapView)。但它不起作用。此片段由ShrlockFragmentActivity启动。 我怎样才能让它发挥作用?

public class CommuneFragment extends SherlockFragment {

Context mContext = getActivity();

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState) ;
    return inflater.inflate(R.layout.commune_map_fragment, container, false);
}


@Override
public void onActivityCreated(final Bundle savedState) {
    super.onActivityCreated(savedState);
    mContext=getActivity();

    View mView = getView();

    //Create the OSM view
    MapView mapView = new MapView(mContext, null);
    //enable zoom in and out on the OSM
    mapView.setClickable(true);
    mapView.setBuiltInZoomControls(true);

    RelativeLayout RL= (RelativeLayout) getActivity().findViewById(R.id.rl);
    RL.addView(mapView);
  }

3 个答案:

答案 0 :(得分:2)

这是因为在添加相对布局之前,您没有提供宽度和高度的地图视图:

RelativeLayout RL= (RelativeLayout) getActivity().findViewById(R.id.rl);
    RL.addView(mapView);

您只需提供宽度和高度为mapview的地图视图:

this.mMapView.setLayoutParams(new LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

解决了我的类似问题。感谢

答案 1 :(得分:0)

我在这个问题中找到了答案: OSMDroid simple example required

但我不知道它不适用于addView

答案 2 :(得分:0)

您可以在onCreateView方法中简单地返回地图视图。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
//init mapView...
return mapView;
}

然后,在您创建de fragmentTransaction的fragmentActivity中,将此视图放在内容framelayout上。

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.container, new CommuneFragment());
            ft.commit();

对不起我的英语,我希望它有所帮助。