引起:java.lang.ClassCastException:com.google.android.gms.maps.SupportMapFragment无法强制转换

时间:2015-03-18 15:21:17

标签: android google-maps

我在android studio中使用片段然后声明类型为customMapFragment的变量MySupportMapFragment

MySupportMapFragment是一个我需要在地图谷歌地图上绘图的类,但在运行应用程序时我收到此错误:

  

“引起:java.lang .ClassCastException:   com.google.android.gms.maps.SupportMapFragment无法转换为   com.juangaviria.juangaviriaconsulta.MySupportMapFragment“

package com.juangaviria.juangaviriaconsulta;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_fragment_mapa, container, false);

    setUpMapIfNeeded();

    MySupportMapFragment customMapFragment = (MySupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
    mMap = customMapFragment.getMap();

    FrameLayout fram_map = (FrameLayout) rootView.findViewById(R.id.fram_map);
    btn_draw_State = (Button) rootView.findViewById(R.id.btn_draw_State);
    btnEnviarPoligono = (Button) rootView.findViewById(R.id.btnEnviarPoligono);

    customMapFragment.setOnDragListener(new MapWrapperLayout.OnDragListener() {

        @Override
        public void onDrag(MotionEvent motionEvent) {
            Log.i("ON_DRAG", "X:" + String.valueOf(motionEvent.getX()));
            Log.i("ON_DRAG", "Y:" + String.valueOf(motionEvent.getY()));

            float x = motionEvent.getX();
            float y = motionEvent.getY();

            int x_co = Integer.parseInt(String.valueOf(Math.round(x)));
            int y_co = Integer.parseInt(String.valueOf(Math.round(y)));

            projection = mMap.getProjection();
            Point x_y_points = new Point(x_co, y_co);
            LatLng latLng = mMap.getProjection().fromScreenLocation(x_y_points);
            latitude = latLng.latitude;
            longitude = latLng.longitude;

            Log.i("ON_DRAG", "lat:" + latitude);
            Log.i("ON_DRAG", "long:" + longitude);

            // Handle motion event:
        }
    });

    btn_draw_State.setText("Activar Dibujo");
    btn_draw_State.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (Is_MAP_Moveable != true) {
                Is_MAP_Moveable = true;
                btn_draw_State.setText("Eliminar Dibujo");
            } else {
                Is_MAP_Moveable = false;
                btn_draw_State.setText("Activar Dibujo");
                val.clear();
                mMap.clear();
                val.add(new LatLng(latitude, longitude));
                btnEnviarPoligono.setEnabled(false);
            }
        }
    });

    btnEnviarPoligono.setEnabled(false);
    btnEnviarPoligono.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            String puntosPoligono = "";
            LatLng obtener;

            for (int i = 0 ; i < val.size() ; i++ )
            {
                obtener = (LatLng) val.get(i);
                puntosPoligono += Integer.toString(i)+" => "+Double.toString(obtener.latitude);
                puntosPoligono += " , "+Double.toString(obtener.longitude);
                puntosPoligono += "\n";
            }
            Log.e("Puntos del poligono: ", puntosPoligono);


        }
    });

    fram_map.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            float x = event.getX();
            float y = event.getY();

            int x_co = Math.round(x);
            int y_co = Math.round(y);

            projection = mMap.getProjection();
            Point x_y_points = new Point(x_co, y_co);

            LatLng latLng = mMap.getProjection().fromScreenLocation(x_y_points);
            latitude = latLng.latitude;

            longitude = latLng.longitude;

            int eventaction = event.getAction();
            switch (eventaction) {
                case MotionEvent.ACTION_DOWN:
                    // finger touches the screen
                    //val.clear();
                    // mMap.clear();
                    // val.add(new LatLng(latitude, longitude));
                    break;

                case MotionEvent.ACTION_MOVE:
                    // finger moves on the screen
                    Draw_Polyline();
                    val.add(new LatLng(latitude, longitude));
                    break;

                case MotionEvent.ACTION_UP:
                    // finger leaves the screen
                    Draw_Map();
                    break;
            }

            if (Is_MAP_Moveable == true) {
                return true;

            } else {
                return false;
            }
        }
    });

    LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        Toast.makeText(getActivity(), "GPS esta activado", Toast.LENGTH_SHORT).show();
    }else{
        showGPSDisabledAlertToUser();
    }
    return rootView;
}

public void Draw_Map() {
    rectOptions = new PolygonOptions();
    rectOptions.addAll(val);
    rectOptions.strokeColor(Color.BLUE);
    rectOptions.strokeWidth(3);
    rectOptions.fillColor(Color.argb(55, 0, 255, 255));
    mMap.clear();
    polygon = mMap.addPolygon(rectOptions);
    btnEnviarPoligono.setEnabled(true);
}

public void Draw_Polyline()
{
    polylineOptions = new PolylineOptions();
    polylineOptions.addAll(val);
    polylineOptions.width(3);
    polylineOptions.color(Color.BLUE);
    mMap.addPolyline(polylineOptions);
}

private void showGPSDisabledAlertToUser(){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    alertDialogBuilder.setMessage("GPS desactivado ¿desea activarlo?")
            .setCancelable(false)
            .setPositiveButton("Ir a configuraciones para activar GPS",
                    new DialogInterface.OnClickListener(){
                        public void onClick(DialogInterface dialog, int id){
                            Intent callGPSSettingIntent = new Intent(
                                    android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(callGPSSettingIntent);
                        }
                    });
    alertDialogBuilder.setNegativeButton("Cancelar",
            new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int id){
                    dialog.cancel();
                }
            });
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
}

@Override
public void onMyLocationChange(Location lastKnownLocation) {
    CameraUpdate myLoc = CameraUpdateFactory.newCameraPosition(
            new CameraPosition.Builder().target(new LatLng(lastKnownLocation.getLatitude(),
                    lastKnownLocation.getLongitude())).zoom(15).build());
    mMap.moveCamera(myLoc);
    mMap.setOnMyLocationChangeListener(null);
}

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

private void setUpMap() {
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.setOnMyLocationChangeListener(this);
    mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Activity activity) {
    //myContext = (FragmentActivity) activity;
    super.onAttach(activity);
    /*try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }*/
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}


/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p/>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
enter code here
    public void onFragmentInteraction(Uri uri);
}
enter code here
enter code here
package com.juangaviria.juangaviriaconsulta;

public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {

    mOriginalContentView = super.onCreateView(inflater, parent, savedInstanceState);
    mMapWrapperLayout = new MapWrapperLayout(getActivity());
    mMapWrapperLayout.addView(mOriginalContentView);
    return mMapWrapperLayout;
}

@Override
public View getView() {
    return mOriginalContentView;
}

public void setOnDragListener(MapWrapperLayout.OnDragListener onDragListener) {
    mMapWrapperLayout.setOnDragListener(onDragListener);
}

1 个答案:

答案 0 :(得分:0)

据推测,res/layout/fragment_fragment_mapa.xmlSupportMapFragment,而不是MySupportMapFragment。编辑您的布局文件以引用您自己的类。