使用片段中的映射时出错

时间:2013-11-16 01:07:14

标签: android map

当我尝试打开我的片段“activityMapa”时出现此错误,显然无法对我的xml文件进行充气:

11-15 21:58:39.769: E/AndroidRuntime(2432): FATAL EXCEPTION: main
11-15 21:58:39.769: E/AndroidRuntime(2432): android.view.InflateException: Binary XML file line #2: Error inflating class fragment
11-15 21:58:39.769: E/AndroidRuntime(2432):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
11-15 21:58:39.769: E/AndroidRuntime(2432):     at android.view.LayoutInflater.inflate(LayoutInflater.java:466)
11-15 21:58:39.769: E/AndroidRuntime(2432):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
11-15 21:58:39.769: E/AndroidRuntime(2432):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
11-15 21:58:39.769: E/AndroidRuntime(2432):     at com.example.despegarteproject.ActivityMapa.onCreateView(ActivityMapa.java:43)
11-15 21:58:39.769: E/AndroidRuntime(2432):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:832)
11-15 21:58:39.769: E/AndroidRuntime(2432):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036)

这就是我在onCreateView中所做的事情:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_mapa, null);


    context = getActivity();

    mapa = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

    mapa.setOnMarkerClickListener(new OnMarkerClickListener() {

        public boolean onMarkerClick(Marker marker) {
            Toast.makeText(context, "Marcador pulsado:\n" + marker.getTitle(), Toast.LENGTH_SHORT).show();
            return false;
        }
    });

    moveTo(40.417325, -3.683081);
    addMarker(40.417325, -3.683081, "Madrid, acá");

    return view;
}

和我的xml文件“acitivty_mapa”:

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

1 个答案:

答案 0 :(得分:0)

创建一个派生自SupportMapFragment的类,您不需要为布局充气。

public class MyMapFragment extends SupportMapFragment {

    private GoogleMap map;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        map = getMap();
    }

然后,当您需要在活动的布局中使用它时,您将在活动的布局xml中引用您的类

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.example.despegarteproject.MyMapFragment" />