【发布时间】:2014-11-02 18:48:11
【问题描述】:
为什么我在执行 GoogleMap map = ((SupportMapFragment) manager.findFragmentById(R.id.map)).getMap() 时会出现空指针异常?我一定遗漏了一些非常明显的东西:
public class ReviewMap extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review_map);
if (savedInstanceState == null) {
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().add(R.id.container, new MapFragment()).commit();
GoogleMap map = ((SupportMapFragment) manager.findFragmentById(R.id.map)).getMap(); // Null pointer exception
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.review_map, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
public static class MapFragment extends Fragment {
public MapFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_review_map, container, false);
return rootView;
}
}
}
我的布局:
activity_review_map.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="atorch.shortestpaths.ReviewMap"
tools:ignore="MergeRootFrame" />
fragment_review_map.xml -- 这是我尝试使用 R.id.map 访问的文件:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
如果我在第一个代码块中注释掉 GoogleMap map = ((SupportMapFragment) manager.findFragmentById(R.id.map)).getMap() 行,一切都会按预期工作(我在 ActionBar 下看到一张地图);如果我留下这一行,我的 logcat 中会出现 Null 指针异常,并且应用程序在显示任何地图之前崩溃。
【问题讨论】:
-
您想在 Activity 中直接使用地图片段,还是想拥有自己的包含 MapView 的自定义片段?如果是前者,直接在activity的布局文件中使用
即可。如果是后者,则需要在 Fragment 的布局文件中包含 com.google.android.gms.maps.MapView。我可以根据您的回答详细说明。 -
前者:我想在我的活动中直接包含一个地图片段。
标签: android google-maps android-fragments