MonoDroid:创建地图片段

时间:2012-10-02 00:50:12

标签: android map mono xamarin.android fragment

我使用以下代码将地图添加到片段

public class MapFragment : Fragment
{
    private MapActivity map=null;
    public override Android.Views.View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        return new FrameLayout(Activity);
    }

    public override void OnActivityCreated(Bundle savedInstanceState)
    {
        base.OnActivityCreated(savedInstanceState);
        map = new MapView(Activity,"XXXXX-v0jt5Z-XXXXXX");
        //HOW TO ADD THE VIEW HERE???
    }
}

我的问题是, Mono for Android 如何将地图添加到视图中。

注意:在Java中我会写这个:

((ViewGroup)getView()).addView(map);

脚注:此示例使用Java MapFragment源代码中的代码:https://github.com/commonsguy/cw-omnibus/blob/master/Maps/NooYawkFragments/src/com/commonsware/android/mapfrags/MapFragment.java

1 个答案:

答案 0 :(得分:0)

地图无法按原样添加到片段,它们需要托管环境。

以下是MapFragment的解决方案:

namespace BahaiResearch.com
{
public class MyMapFragment : Fragment
{
    // FROM http://stackoverflow.com/questions/5109336/mapview-in-a-fragment-honeycomb
    private static  String KEY_STATE_BUNDLE = "localActivityManagerState";

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        Bundle state = null;
        if (savedInstanceState != null) {
            state = savedInstanceState.GetBundle(KEY_STATE_BUNDLE);
        }
        mLocalActivityManager = new LocalActivityManager(Activity, true);
        mLocalActivityManager.DispatchCreate(state);
    }

    public override Android.Views.View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        //This is where you specify you activity class
        Intent i = new Intent(Activity, typeof(SteamLocationMapActivity)); 
        Window w = mLocalActivityManager.StartActivity("tag", i); 
        View currentView=w.DecorView; 
        currentView.Visibility = ViewStates.Visible; 
        currentView.FocusableInTouchMode = true; 
        ((ViewGroup) currentView).DescendantFocusability = DescendantFocusability.AfterDescendants;
        return currentView;
    }

    private LocalActivityManager mLocalActivityManager;
    protected LocalActivityManager GetLocalActivityManager() {
        return mLocalActivityManager;
    }   


    public override void OnSaveInstanceState(Bundle outState)
    {
        base.OnSaveInstanceState(outState);
        outState.PutBundle(KEY_STATE_BUNDLE,mLocalActivityManager.SaveInstanceState());
    }

    public override void OnResume()
    {
        base.OnResume();
        mLocalActivityManager.DispatchResume();

    }

    public override void OnPause()
    {
        base.OnPause();
        mLocalActivityManager.DispatchPause(Activity.IsFinishing);
    }

    public override void OnStop()
    {
        base.OnStop();
        mLocalActivityManager.DispatchStop();
    }
}
}