错误膨胀片段问题

时间:2014-04-29 10:00:49

标签: java android android-fragments android-fragmentactivity

我有一个正在处理的项目但是当我尝试启动包含地图的活动时出现此错误。

以下是我从logCat获得的内容:

04-29 11:55:39.588: E/AndroidRuntime(11635): FATAL EXCEPTION: main
04-29 11:55:39.588: E/AndroidRuntime(11635): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.scsp/com.scsp.Map}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.app.ActivityThread.access$600(ActivityThread.java:127)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.os.Looper.loop(Looper.java:137)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.app.ActivityThread.main(ActivityThread.java:4441)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at java.lang.reflect.Method.invokeNative(Native Method)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at java.lang.reflect.Method.invoke(Method.java:511)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at dalvik.system.NativeStart.main(Native Method)
04-29 11:55:39.588: E/AndroidRuntime(11635): Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.view.LayoutInflater.parseInclude(LayoutInflater.java:823)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:729)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.app.Activity.setContentView(Activity.java:1835)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at com.scsp.Map.onCreate(Map.java:64)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.app.Activity.performCreate(Activity.java:4465)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
04-29 11:55:39.588: E/AndroidRuntime(11635):    ... 11 more
04-29 11:55:39.588: E/AndroidRuntime(11635): Caused by: java.lang.ClassCastException: com.google.android.gms.maps.MapFragment cannot be cast to android.support.v4.app.Fragment
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.support.v4.app.Fragment.instantiate(Fragment.java:394)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.support.v4.app.Fragment.instantiate(Fragment.java:369)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:272)
04-29 11:55:39.588: E/AndroidRuntime(11635):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:669)
04-29 11:55:39.588: E/AndroidRuntime(11635):    ... 24 more

我已从项目中的libs文件夹中删除了android-support-v4.jar,但我看到该文件位于我使用的库中。谁能告诉我怎么解决这个问题?

我的地图活动代码:

public class Map extends FragmentActivity {
    private GoogleMap map;
    private ArrayList<Servizi> servizi;
    private ArrayList<MainScreenObject> mainObj;
    private ArrayList<Marker> serviziMarkers;
    private ArrayList<Marker> blackMarkers;
    private ArrayList<Marker> redMarkers;
    private CheckBox black, red, green;
    // private Marker myLocationMarker;
    private TextView screenTitle;
    private static final int RAD = 6371000;
    private boolean centered = false;
    private Button centra, external;
    private Location myLocation;

    CameraPosition myPosition;

    SlidingDrawer slidingDrawer;
    ImageView slideButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_test);
        // Enabling Up / Back navigation

        try {
            // Loading map

            initilizeMap();
            initWidtets();

            map.setMyLocationEnabled(true);
            map.getUiSettings().setMyLocationButtonEnabled(false);
            // Location myLocation = map.getMyLocation();

            centerMapOnMyLocation();

            map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
                @Override
                public void onInfoWindowClick(Marker marker) {
                    // startactivity and pass data here
                    Toast.makeText(Map.this, "BOOM!", Toast.LENGTH_SHORT)
                            .show();
                }
            });
            if (getParent().getClass().equals(Main.class)) {
                slidingDrawer.setVisibility(View.GONE);
            }
            slidingDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
                @Override
                public void onDrawerOpened() {
                    slideButton.setBackgroundResource(R.drawable.close);
                }
            });
            slidingDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
                @Override
                public void onDrawerClosed() {
                    slideButton.setBackgroundResource(R.drawable.semnal);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void centerMapOnMyLocation() {

        map.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

            @Override
            public void onMyLocationChange(Location arg0) {

                LatLng myLatLng = new LatLng(arg0.getLatitude(), arg0
                        .getLongitude());
                myPosition = new CameraPosition.Builder().target(myLatLng)
                        .zoom(17).bearing(0).tilt(30).build();
                if (!centered) {
                    myLocation = arg0;
                    map.animateCamera(CameraUpdateFactory
                            .newCameraPosition(myPosition));
                    centered = true;
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        overridePendingTransition(R.anim.slide_in_down, R.anim.slide_out_down);
    }

    private double getDistance(double lat1, double lon1, double lat2,
            double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);

        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2)
                * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);

        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return RAD * c;
    }

    private void initWidtets() {
        Typeface typeFaceRegular = Typeface.createFromAsset(getAssets(),
                "CaviarDreams.ttf");
        servizi = getIntent().getParcelableArrayListExtra(Constants.SERVIZI);
        mainObj = getIntent().getParcelableArrayListExtra(
                Constants.MAIN_ARR_OBJ);

        serviziMarkers = new ArrayList<Marker>();
        blackMarkers = new ArrayList<Marker>();
        redMarkers = new ArrayList<Marker>();
        black = (CheckBox) findViewById(R.id.checkBox1);
        black.setTypeface(typeFaceRegular);
        green = (CheckBox) findViewById(R.id.checkBox3);
        green.setTypeface(typeFaceRegular);
        red = (CheckBox) findViewById(R.id.checkBox2);
        red.setTypeface(typeFaceRegular);
        centra = (Button) findViewById(R.id.map_centra);
        external = (Button) findViewById(R.id.map_external);
        external.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri
                        .parse("http://maps.google.com/maps?f=d&daddr="
                                + servizi.get(0).getLat() + ","
                                + servizi.get(0).getLon()));
                intent.setComponent(new ComponentName(
                        "com.google.android.apps.maps",
                        "com.google.android.maps.MapsActivity"));
                startActivity(intent);
            }
        });
        centra.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                map.animateCamera(CameraUpdateFactory
                        .newCameraPosition(myPosition));
            }
        });
        green.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                toggleMarkers(serviziMarkers);
            }
        });

        black.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                toggleMarkers(blackMarkers);
            }
        });

        red.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                toggleMarkers(redMarkers);
            }
        });
        if (servizi != null)
            addServiziMarkers();
        if (mainObj != null) {
            addBlackMarkers();
            addRedMarkers();
        }

        // Enabling Up / Back navigation
        getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getActionBar().setDisplayShowCustomEnabled(true);
        View cView = getLayoutInflater().inflate(R.layout.actionbar_map, null);
        getActionBar().setCustomView(cView);
        screenTitle = (TextView) findViewById(R.id.menu_title);
        screenTitle.setText(getString(R.string.smart_map));

    }

    private void toggleMarkers(ArrayList<Marker> markers) {
        for (int i = 0; i < markers.size(); i++) {
            if (markers.get(i).isVisible())
                markers.get(i).setVisible(false);
            else
                markers.get(i).setVisible(true);
        }
    }

    private void addBlackMarkers() {
        Marker m;
        Log.v("--", "BLACK MARKERS SIZE: "
                + mainObj.get(0).getAddi_info().getTasks().size());
        for (int i = 0; i < mainObj.get(0).getAddi_info().getTasks().size(); i++) {
            Tasks task = mainObj.get(0).getAddi_info().getTasks().get(i);
            m = map.addMarker(new MarkerOptions()
                    .position(new LatLng(task.getLat(), task.getLon()))
                    .title(task.getTitle())
                    .icon(BitmapDescriptorFactory.fromResource(Constants
                            .GetImage(this, "addb" + task.getId()))));
            blackMarkers.add(m);
        }
    }

    private void addRedMarkers() {
        Marker m;
        Log.v("--", "RED MARKERS SIZE: "
                + mainObj.get(1).getAddi_info().getTasks().size());
        for (int i = 0; i < mainObj.get(1).getAddi_info().getTasks().size(); i++) {
            Tasks task = mainObj.get(1).getAddi_info().getTasks().get(i);
            m = map.addMarker(new MarkerOptions()
                    .position(new LatLng(task.getLat(), task.getLon()))
                    .title(task.getTitle())
                    .icon(BitmapDescriptorFactory.fromResource(Constants
                            .GetImage(this, "addn" + task.getId()))));
            redMarkers.add(m);
        }
    }

    private void addServiziMarkers() {
        Marker m;

        for (int i = 0; i < servizi.size(); i++) {
            m = map.addMarker(new MarkerOptions()
                    .position(
                            new LatLng(servizi.get(i).getLat(), servizi.get(i)
                                    .getLon()))
                    .title(servizi.get(i).getTitle())
                    .icon(BitmapDescriptorFactory.fromResource(Constants
                            .GetImage(this, "addg" + servizi.get(i).getId()))));
            serviziMarkers.add(m);
        }
    }

    /**
     * function to load map. If map is not created it will create it for you
     * */
    private void initilizeMap() {
        if (map == null) {
            map = ((MapFragment) getFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            // map.setMyLocationEnabled(true); // Enable the my-location layer

            // check if map is created successfully or not
            if (map == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    public void clickEvent(View v) {
        switch (v.getId()) {
        case R.id.menu_back:
            this.finish();
            overridePendingTransition(R.anim.slide_in_down,
                    R.anim.slide_out_down);
            break;
        case R.id.menu_penuta:
            Toast.makeText(this, "Here what?", Toast.LENGTH_SHORT).show();
            break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

我的xml布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/fragment_placeholder"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <include
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            layout="@layout/map" />
    </FrameLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent" >

        <SlidingDrawer
            android:id="@+id/SlidingDrawer"
            android:layout_width="wrap_content"
            android:layout_height="240dip"
            android:layout_gravity="bottom"
            android:content="@+id/contentLayout"
            android:handle="@+id/slideButton"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/slideButton"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:scaleType="fitEnd"
                android:src="@drawable/semnal" />

            <LinearLayout
                android:id="@+id/contentLayout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@android:color/white"
                android:orientation="vertical"
                android:padding="10dp" >

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal" >

                    <Button
                        android:id="@+id/map_centra"
                        android:layout_width="40dp"
                        android:layout_height="40dp"
                        android:layout_margin="5dp"
                        android:background="@drawable/centra" />

                    <Button
                        android:id="@+id/map_external"
                        android:layout_width="40dp"
                        android:layout_height="40dp"
                        android:layout_margin="5dp"
                        android:background="@drawable/naviga" />

                    <ToggleButton
                        android:id="@+id/bus_btn"
                        android:layout_width="40dp"
                        android:layout_height="40dp"
                        android:layout_margin="5dp"
                        android:background="@android:color/transparent"
                        android:button="@drawable/bus_sel"
                        android:textOff=""
                        android:textOn="" />

                    <ToggleButton
                        android:id="@+id/car_btn"
                        android:layout_width="40dp"
                        android:layout_height="40dp"
                        android:layout_margin="5dp"
                        android:background="@android:color/transparent"
                        android:button="@drawable/car_sel"
                        android:textOff=""
                        android:textOn="" />

                    <ToggleButton
                        android:id="@+id/walk_btn"
                        android:layout_width="40dp"
                        android:layout_height="40dp"
                        android:layout_margin="5dp"
                        android:background="@android:color/transparent"
                        android:button="@drawable/walk_sel"
                        android:textOff=""
                        android:textOn="" />
                </LinearLayout>

                <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dp" android:text="Lorem ispum doloret si amet."/>
            </LinearLayout>
        </SlidingDrawer>
    </FrameLayout>

</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

您扩展FragmentActivity并拥有

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

您应该使用SupportMapFragmentFragmentActivity是基于支持的Fragments的基类。

  map = ((SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map)).getMap();

您还需要导入com.google.android.gms.maps.SupportMapFragment

确保您在xml中也有SupportMapFragment

答案 1 :(得分:0)

尝试以下代码: -

GoogleMap map;
SupportMapFragment mapFragment;
android.support.v4.app.FragmentManager fragmentManager;

fragmentManager = this.getSupportFragmentManager();// use getActivity() instead of this when you work on fragment only
mapFragment = (SupportMapFragment) fragmentManager.findFragmentById(R.id.map);
map = mapFragment.getMap();