28

我在地图位于第二个位置的下拉导航活动中使用 Google Maps API V2。

我正在务实地添加地图,例如:

mMapFragment = supportMapFragment.newInstance();
getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.placeHolder, mMapFragment, TAG_MAP)
        .commit(); 

我想获得 GoogleMap ovject,因为文档https://developers.google.com/maps/documentation/android/map说它应该用 完成mMapFragment.getMap(),但它返回 null。

根据http://developer.android.com/reference/com/google/android/gms/maps/SupportMapFragment.html 如果 Fragment 没有经历 onCreateView 生命周期事件,它会返回 null。

我怎么知道片段何时准备好?

编辑:我发现这个我如何知道使用 SupportMapFragment 时地图已准备好使用?

覆盖 onActivityCreated 似乎是一个解决方案,但是我必须通过构造函数而不是使用 newInstance() 来实例化片段,这有什么区别吗?

4

4 回答 4

47

我首选的方法是使用回调从Fragment. 另外,这是 Android 在与 Activity 通信时提出的推荐方法

对于您的示例,在您的 中Fragment,添加一个接口并注册它。

public static interface OnCompleteListener {
    public abstract void onComplete();
}

private OnCompleteListener mListener;

public void onAttach(Context context) {
    super.onAttach(context);
    try {
        this.mListener = (OnCompleteListener)context;
    }
    catch (final ClassCastException e) {
        throw new ClassCastException(context.toString() + " must implement OnCompleteListener");
    }
}

现在在你的实现这个接口Activity

public class MyActivity extends FragmentActivity implements MyFragment.OnCompleteListener {
    //...

    public void onComplete() {
        // After the fragment completes, it calls this callback.
        // setup the rest of your layout now
        mMapFragment.getMap()
    }
}

现在,无论你在什么Fragment地方表示它已经加载,通知你Activity它已经准备好了。

@Override
protected void onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // create your fragment
    //...

    // signal that you're done and tell the Actvity to call getMap()
    mListener.onComplete();
}

编辑2017-12-05 onAttach(Activity activity) 已弃用,请改用 onAttach(Context context)。上面的代码已调整。

于 2013-02-21T16:42:18.303 回答
2

除了柯克的回答:因为public void onAttach(Activity activity)已弃用,您现在可以简单地使用:

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    Activity activity;

    if (context instanceof Activity){

        activity=(Activity) context;

        try {
            this.mListener = (OnCompleteListener)activity;
        } catch (final ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnCompleteListener");
        }
    }
}

其余的保持不变......尽管有人可能希望将其(Fragment sender)用作参数并始终传递this.

于 2017-03-19T11:14:02.747 回答
1

如果你想在没有任何监听器的情况下这样做:

添加带有标签的片段

 supportFragmentManager
                .beginTransaction()
                .add(R.id.pagerContainer, UniversalWebViewFragment.newInstance(UniversalWebViewFragment.YOUTUBE_SERACH_URL+"HD trailers"), 
                "UniversalWebView")
                .disallowAddToBackStack()
                .commit()

在加载片段后要调用的 Hosting Activity 类中创建一个公共方法。在这里,我正在回调我的片段的方法,例如

public fun loadURL() {
        val webViewFragment = supportFragmentManager
                              .findFragmentByTag("UniversalWebView") 
                               as UniversalWebViewFragment

        webViewFragment.searchOnYoutube("Crysis Warhead")
    }

现在在onViewCreated片段的 Method 中,您可以像这样简单地调用 Host 活动的公共方法:

    (activity as HomeActivity ).loadURL()
于 2019-01-29T10:58:28.530 回答
0

我不确定我是否完全理解您的问题,但我有一个类似的设置,我正在使用导航下拉菜单。这对我有用:

1.) 从 xml 文件加载片段并调用 setupMapIfNeeded()

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.basicMap);

setUpMapIfNeeded();

这是供参考的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/basicMap"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  class="com.google.android.gms.maps.SupportMapFragment" />

2.) 然后设置地图(有关 isGoogleMapsInstalled() 的详细信息,请参阅此问题

    private void setUpMapIfNeeded() 
    {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) 
    {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.basicMap)).getMap();
        // Check if we were successful in obtaining the map.
        if(isGoogleMapsInstalled())
        {
            if (mMap != null) 
            {
                mMap.setOnCameraChangeListener(getCameraChangeListener());
                mMap.setInfoWindowAdapter(new MyCustomInfoWindowAdapter(this));
            }
        }
        else
        {
            MapConstants.showDialogWithTextAndButton(this, R.string.installGoogleMaps, R.string.install, false, getGoogleMapsListener());
        }
    }
    }

3.) 确保您还从 onResume() 调用 setUpMapIfNeeded():

public void onResume()
{
    super.onResume();

    setUpMapIfNeeded();
}
于 2013-02-21T16:25:38.163 回答