2012-12-20 79 views
0

我試圖在片段的onActivityCreated中的一個relativeLayout中添加MapView(org.osmdroid.views.MapView)。但它不起作用。這個片段由ShrlockFragmentActivity啓動。 如何讓它工作?Mapview osmdroid在片段中不可見

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); 
    } 

回答

0

工作,你可以簡單的返回在onCreateView方法的地圖視圖。

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

然後,在你fragmentActivity,你做去fragmentTransaction,你把內容的FrameLayout這個觀點。

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

對不起,我的英語,我希望它可以幫助。

2

那是因爲你還沒有相對佈局前加入提供了寬度和高度的地圖視圖:

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

所有你需要的是提供的MapView寬度和高度爲:

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

用這個解決了我的類似問題。謝謝