我正在尝试使用Google Play服务在Activity
中显示地图
但当我开始Activity
时,它会给我RunTimeException
这是Java代码:
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.Fragment;
import android.widget.Toast;
public class MyMap extends FragmentActivity {
private GoogleMap googleMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.my_map);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
@Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
这是布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
以下是LogCat在启动Activity
时所说的内容:
06-01 03:33:59.207: E/AndroidRuntime(2744): FATAL EXCEPTION: main
06-01 03:33:59.207: E/AndroidRuntime(2744): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.tracker/com.project.tracker.MyMap}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
06-01 03:33:59.207: E/AndroidRuntime(2744): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2313)
06-01 03:33:59.207: E/AndroidRuntime(2744): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
06-01 03:33:59.207: E/AndroidRuntime(2744): at android.app.ActivityThread.access$600(ActivityThread.java:156)
06-01 03:33:59.207: E/AndroidRuntime(2744): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
06-01 03:33:59.207: E/AndroidRuntime(2744): at android.os.Handler.dispatchMessage(Handler.java:99)
答案 0 :(得分:2)
你应该改变这个
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
到
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
并且还要改变
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
到
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();