我创建了一个演示该问题的Github项目。
git clone https://github.com/anujgoyal/buggymap.git
我意识到存在一些问题,但很少有人将这个程序提升到这个水平。此外,我强烈要求使用 android.support.v4.app.Fragment 类,而不是 FragmentActivity ,而不是 MapFragment 。
请注意,您必须在AndroidManifest.xml中更改com.google.android.maps.v2.API_KEY
的android:值
为什么SupportMapFragment为NULL?
// MainActivity.java
package com.txt2lrn.buggymap;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public static class PlaceholderFragment extends Fragment implements OnMapReadyCallback {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
//SupportMapFragment smf0 =
// (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
SupportMapFragment smf1 =
(SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
SupportMapFragment smf2 =
(SupportMapFragment)
getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
Log.d("maps", "smf1: "+smf1); // always NULL
Log.d("maps", "smf2: "+smf2); // always NULL
//smf.getMapAsync(this);
return rootView;
}
@Override
public void onMapReady(GoogleMap map) {
// code will go here once getMapAsync works
}
}
}
这是fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<fragment
android:id="@+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
答案 0 :(得分:2)
您似乎正在尝试使用嵌套片段。在这种情况下,您可以通过在您的片段上调用的FragmentManager
返回的getChildFragmentManager()
获取这些嵌套片段,而不是在您的活动中调用getSupportFragmentManager()
。