【发布时间】:2014-12-16 23:23:44
【问题描述】:
我想在地图中的两个位置之间添加标记并绘制一条折线,问题是当我尝试从 Fragment 类引用 Googlemap 时引发异常。
就像这样,我有一个扩展了 Fragment 类的类,并且使用普通的 xml 布局设置了 Fragment 类的视图。此外,此布局包含一个片段,这是 google 地图所在的位置。
这是保存地图片段的片段的布局代码;
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:background="#ffffff"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="20dp"
>
<EditText
android:id="@+id/from"
android:layout_width="300dp"
android:layout_gravity="center"
android:hint="Enter the starting location"
android:layout_height="wrap_content"></EditText>
<Button
android:id="@+id/btn_showDirections"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:text="Show Directions"
android:layout_height="wrap_content" />
<fragment
android:layout_width="match_parent"
android:tag="HelloMap"
android:layout_height="300dp"
android:layout_margin="10dp"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
/>
</LinearLayout>
这是连接到给定布局文件的类
public class frg_planVisit_directionsToZoo extends Fragment {
GoogleMap mMap;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
try{
mMap = ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
}
catch (Exception exp)
{
Log.i("Chin",exp.toString());
}
return inflater.inflate(R.layout.frg_planvisit_directions_to_zoo,container,false);
}
}
包含地图片段的片段已连接到活动并且工作正常。在我获得对谷歌地图的引用的代码中引发了异常。
mMap = ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
如果这是错误的,有人可以帮我获取地图的参考吗?我是 Android 新手。
为了您的方便,我将在堆栈跟踪中发布一些重要的内容。
*12-17 04:00:24.533 19369-19369/com.android.ZooCeylon I/Chin﹕ java.lang.NullPointerException
12-17 04:00:25.423 19369-19374/com.android.ZooCeylon E/dalvikvm﹕ GC_CONCURRENT freed 359K, 8% free 13026K/14087K, paused 13ms+4ms, total 40ms
12-17 04:00:25.583 19369-19374/com.android.ZooCeylon E/dalvikvm﹕ GC_CONCURRENT freed 870K, 11% free 13647K/15239K, paused 7ms+15ms, total 64ms
12-17 04:00:26.013 19369-19369/com.android.ZooCeylon W/System.err﹕ Invalid int: ""
12-17 04:00:27.943 19369-19369/com.android.ZooCeylon I/Choreographer﹕ Skipped 207 frames! The application may be doing too much work on its main thread.
12-17 04:00:30.173 19369-19614/com.android.ZooCeylon W/System.err﹕ java.lang.NullPointerException*
【问题讨论】:
-
1) 尝试将
findFragmentById(...)代码移动到onViewCreated。仅增加onCreateView中的视图。如果这不起作用,请尝试将其移至onStart。 2) 使用SupportMapFragment.getMapAsync(...),这样您就可以保证收到GoogleMap实例。
标签: android google-maps android-layout fragment mapfragment