碎片之间的导航问题

时间:2016-01-24 21:09:10

标签: android-fragments navigation onbackpressed

嗨我有一个背部按钮的问题,我有一个主抽屉打开我的主片段,每次我改变我的片段我称为addToBackStack(null)问题它与导航抽屉当我在第二个片段和在我的抽屉上选择fisrt选项,片段显示正确,但在那之后我按回buttom并得到:

01-24 18:40:16.522 12825-12825 /? E / AndroidRuntime:致命异常:主要                                                    流程:ar.com.taxiexpress.taxiexpress,PID:12825                                                    android.view.InflateException:二进制XML文件行#6:错误膨胀类片段                                                        在android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)                                                        在android.view.LayoutInflater.rInflate(LayoutInflater.java:755)                                                        在android.view.LayoutInflater.inflate(LayoutInflater.java:492)                                                        在android.view.LayoutInflater.inflate(LayoutInflater.java:397)                                                        在ar.com.taxiexpress.taxiexpress.MapaChofer.onCreateView(MapaChofer.java:80)                                                        在android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)                                                        在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)                                                        在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)...

这是我的代码:

主抽屉:

public class DrawerPrincipal extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,FragmentoPrincipalUsuario.OnFragmentInteractionListener {


    private ParseFile mPrueba;
    private Uri url;
    private ImageView imagen;
    SharedPreferences sharedPref;
    SharedPreferences.Editor  loginStateEditor ;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drawer_principal);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        ParseUser usuario= ParseUser.getCurrentUser();
    if(usuario==null){
        Intent intento=new Intent(this,ActividadLogin.class);
        intento.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intento.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intento);

    }





        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        View hView =  navigationView.inflateHeaderView(R.layout.nav_header_drawer_principal);
        final ImageView imgvw = (ImageView)hView.findViewById(R.id.imagenPerfil);
        final TextView tv = (TextView)hView.findViewById(R.id.nombreUsuarioV);
        //Picasso.with(getBaseContext()).load(url.toString()).into(imgvw);
        tv.setText("new text");

        ParseQuery<ParseUser> query2 = ParseUser.getQuery();
        query2.whereEqualTo("username","gaspar@gmail.com");
        query2.findInBackground(new FindCallback<ParseUser>() {
            public void done(List<ParseUser> usuario, ParseException e) {
                if (e == null) {

                    mPrueba = usuario.get(0).getParseFile("foto");
                    tv.setText(usuario.get(0).getUsername().toString());
                    url = Uri.parse(mPrueba.getUrl());
                    Picasso.with(getBaseContext()).load(url.toString()).transform(new RoundedTransformation(300, 4)).into(imgvw);


                } else {
                    // Something went wrong.
                }
            }
        });




        //fragmento del chofer




            Fragment fragmento;
            fragmento = new FragmentoPrincipalChofer();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_main, fragmento)
                    .commit();




    }






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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.cuenta) {

            Fragment fragmento;
            fragmento = new OpcionDrawerUsuario();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_main, fragmento)
                    .addToBackStack(null)
                    .commit();

        } else if (id == R.id.historial_viajes) {
            Fragment fragmento;
            fragmento = new FragmentoViajesAcumulados();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_main, fragmento)
                    .commit();


        } else if (id == R.id.contacto) {
            String emailAdress[] = {"gastondelacruz@gmail.com"};
            Intent email= new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_EMAIL,emailAdress);
            email.putExtra(Intent.EXTRA_SUBJECT,"Pon aqui el motivo de tu mail");
            email.setType("text/plain");
            email.putExtra(Intent.EXTRA_TEXT,"Su mensaje");
            startActivity(email);


        } else if (id == R.id.compartir) {
            String texto="https://www.google.com.ar/?gfe_rd=cr&ei=9JuBVvmcGanX8gejsK_4CA&gws_rd=ssl";
            Intent intento= new Intent();
            intento.setAction(Intent.ACTION_SEND);
            intento.putExtra(Intent.EXTRA_TEXT, texto);
            intento.setType("text/plain");
            startActivity(intento);

        } else if (id == R.id.version) {
            String prueba="aceptar";
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("prueba") //
                    .setMessage("Esta es una prueba todavia no poseo el numero de version del producto") //
                    .setPositiveButton(prueba, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // TODO
                            dialog.dismiss();
                        }
                    }); //

            builder.show();

        } else if (id == R.id.salir) {

            finish();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}

主要片段:

public class FragmentoPrincipalChofer extends ListFragment {
    private List<ParseObject> mPedido;
    private List<ParseObject> mViaje;
    private List<ParseUser> mUrlUsuario;
    private ListView mLista;
    private Runnable r;
    final Handler handler = new Handler();





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


        View x = inflater.inflate(R.layout.fragmento_principal_chofer, container, false);
        mLista = (ListView)x.findViewById(android.R.id.list);

        return x;

    }

    @Override
    public void onResume() {
        super.onResume();


        // logica de recibir pedidos



            r = new Runnable() {
                public void run() {

                    handler.postDelayed(r, 10000);




                    //obtener pedido de taxi
                    ParseQuery<ParseObject> query = ParseQuery.getQuery("Pedido");
                    query.whereEqualTo("chofer", "chofer1");
                    query.addDescendingOrder("createdAt");
                    query.findInBackground(new FindCallback<ParseObject>() {
                        public void done(List<ParseObject> pedido, com.parse.ParseException e) {
                            if (e == null) {
                                mPedido = pedido;
                                String[] nombreUsuarios = new String[mPedido.size()];
                                int i = 0;
                                for (ParseObject pedidos : mPedido) {

                                    nombreUsuarios[i] = pedidos.getString("cliente");
                                    i++;

                                }



                                AdaptadorDatosListviewChofer adaptador = new AdaptadorDatosListviewChofer(getListView().getContext(), mPedido);
                                setListAdapter(adaptador);

                            } else {

                            }
                        }
                    });

                }
            };
            r.run();






        ClickPedido();



    }



// manejo de click sobre el pedido de taxi
    public void ClickPedido(){

        mLista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Fragment fragment2 = new MapaChofer();
                FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                transaction.replace(R.id.prueba2, fragment2).addToBackStack(null);
                transaction.commit();
/*
                DrawerPrincipal prueba=new DrawerPrincipal();
                prueba.cambiarFragmento();*/


                //verificar si aun existe el pedido en la base de datos
               /* final String clienteSeleccionado = (String) mLista.getItemAtPosition(position);
                ParseQuery<ParseObject> query = ParseQuery.getQuery("Pedido");
                query.whereEqualTo("usuario", clienteSeleccionado);
                query.findInBackground(new FindCallback<ParseObject>() {
                    public void done(List<ParseObject> pedido, com.parse.ParseException e) {
                        if (e == null) {
                            //guardar viaje tomado por chofer
                            ParseObject Viaje = new ParseObject("Viaje");
                            Viaje.put("chofer", "chofer1");
                            Viaje.put("cliente", clienteSeleccionado);
                            Viaje.saveInBackground();


                            //borrar pedido xque paso a viaje


                            ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Pedido");
                            query.whereEqualTo("cliente", clienteSeleccionado);
                            query.getFirstInBackground(new GetCallback<ParseObject>() {
                                @Override
                                public void done(ParseObject pedido, ParseException e) {
                                    try {
                                        pedido.delete();
                                        pedido.saveInBackground();
                                    } catch (ParseException ex) {
                                        ex.printStackTrace();
                                    }
                                }
                            });

                        } else {
                            //debo cambiarlo por un dialog
                            Toast.makeText(getContext(), "el pedido ya fue tomado", Toast.LENGTH_LONG).show();
                        }
                    }
                });*/

            }
        });


    }
    @Override
    public void onPause() {
        super.onPause();
        handler.removeCallbacks(r);
    }

}

第二个片段:

   public class MapaChofer extends Fragment implements OnMapReadyCallback {

    private SupportMapFragment sMapFragment;
    private Runnable r;
    final Handler handler = new Handler();
    private String mDireccion;
    private GoogleMap mMapaTaxi;
    private Marker mMarcadorTaxi;
    private Marker mMarcadorCliente;
    public boolean mCambiarPosicion = false;
    private Button mCancelar;
    private Button mTomado;
    private ParseFile mPrueba;
    private Uri url;
    private ImageView mUsuario;
    private TextView mNUsuario;
    private Double mLatitud;
    private Double mLongitud;
    private Double mLatitudCliente;
    private Double mLongitudCliente;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //conseguir usuario actual
        // mUsuarioActual = ParseUser.getCurrentUser();

        //preparar google maps
        final View x = inflater.inflate(R.layout.mapa_chofer, container, false);
        mCancelar = (Button) x.findViewById(R.id.cancelarPedido);
        mTomado = (Button) x.findViewById(R.id.pTomadoBtn);
        mUsuario = (ImageView) x.findViewById(R.id.usuarioIv);
        mNUsuario = (TextView) x.findViewById(R.id.usuarioNTv);
        mTomado.setEnabled(false);

        ParseUser currentUser = ParseUser.getCurrentUser();
        currentUser.logOut();

        ParseUser.logInInBackground("chofer1", "12345", new LogInCallback() {
            public void done(ParseUser user, ParseException e) {
                if (user != null) {
                    // Hooray! The user is logged in.
                } else {
                    // Signup failed. Look at the ParseException to see what happened.
                }
            }
        });


        ParseQuery<ParseUser> query2 = ParseUser.getQuery();
        query2.whereEqualTo("username", "gaspar@gmail.com");
        query2.findInBackground(new FindCallback<ParseUser>() {
            public void done(List<ParseUser> usuario, ParseException e) {
                if (e == null) {

                    mPrueba = usuario.get(0).getParseFile("foto");
                    mNUsuario.setText(usuario.get(0).getUsername().toString());
                    url = Uri.parse(mPrueba.getUrl());
                    Picasso.with(getContext()).load(url.toString()).transform(new RoundedTransformation(300, 4)).into(mUsuario);


                } else {
                    // Something went wrong.
                }
            }
        });


        sMapFragment = SupportMapFragment.newInstance();
        sMapFragment.getMapAsync(this);
        android.support.v4.app.FragmentManager fm = getFragmentManager();
        android.support.v4.app.FragmentManager sFm = getChildFragmentManager();
        sFm.beginTransaction().add(R.id.mapaChofer, sMapFragment).commit();


        //controlar pedido

        seguirPedido();










        return x;

    }


    public void seguirPedido() {


        // mMarcadorTaxi = mMapaTaxi.addMarker(new MarkerOptions().position(sydney));
        r = new Runnable() {
            public void run() {

                handler.postDelayed(r, 10000);
                ParseQuery<ParseUser> query = ParseUser.getQuery();
                query.whereEqualTo("username", "chofer1");
                query.findInBackground(new FindCallback<ParseUser>() {
                    public void done(final List<ParseUser> objects, ParseException e) {
                        if (e == null) {
                            Double longitud = Double.parseDouble(objects.get(0).get("longitud").toString());
                            Double latitud = Double.parseDouble(objects.get(0).get("latitud").toString());



                            if (mCambiarPosicion == true) {

                                //obtener la posicion actual
                                posicionActual();



                                final ParseUser usuario = ParseUser.getCurrentUser();
                                usuario.put("longitud", mLongitud);
                                usuario.put("latitud", mLatitud);
                                usuario.saveInBackground(new SaveCallback() {
                                    @Override
                                    public void done(ParseException e) {
                                        if (e == null) {
                                            //success, saved!

                                        } else {
                                            //fail to save!

                                        }
                                    }
                                });



                                mMarcadorTaxi.remove();
                                LatLng posicionTaxista = new LatLng(mLatitud, mLongitud);
                                mMarcadorTaxi = mMapaTaxi.addMarker(new MarkerOptions().position(posicionTaxista));


                                Location prueba1 = new Location("punto a");
                                prueba1.setLongitude(mLongitud);
                                prueba1.setLatitude(mLatitud);

                                Location prueba2 = new Location("punto a");
                                prueba2.setLongitude(mLongitudCliente);
                                prueba2.setLatitude(mLatitudCliente);



                                float distance;
                                distance = prueba1.distanceTo(prueba2);


                                if (distance < 300) {
                                    Toast.makeText(getContext(), "El taxi se encuentra a 1 cuadra", Toast.LENGTH_LONG).show();
                                    mTomado.setEnabled(true);
                                    mTomado.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            getFragmentManager().popBackStack();


                                        }
                                    });
                                }


                            } else {
                                posicionActual();
                                LatLng posicionTaxista = new LatLng(mLatitud,mLongitud );
                                mMarcadorTaxi = mMapaTaxi.addMarker(new MarkerOptions().position(posicionTaxista));


                            }

                            // handler.removeCallbacks(r);
                            // mTomado=true;
                            // Toast.makeText(getContext(),mLongitud+"",Toast.LENGTH_LONG).show();
                            mCambiarPosicion = true;
                        } else {
                            // Something went wrong.
                        }
                    }
                });


            }
        };
        r.run();


    }
    // mMarcadorTaxi.remove();


    @Override
    public void onMapReady(final GoogleMap googleMap) {

        if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        googleMap.setMyLocationEnabled(true);
        Double longitud=-27.793483;
        Double latitud=-64.257572;
        final LatLng ubicacion = new LatLng(latitud,longitud );
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ubicacion,14 ));
        mMapaTaxi = googleMap;



        ParseQuery<ParseUser> query = ParseUser.getQuery();
        query.whereEqualTo("username", "gaspar@gmail.com");
        query.findInBackground(new FindCallback<ParseUser>() {
            @Override
            public void done(List<ParseUser> objects, ParseException e) {
                Double longitud = Double.parseDouble(objects.get(0).get("longitud").toString());
                Double latitud = Double.parseDouble(objects.get(0).get("latitud").toString());


                final LatLng ubicacion = new LatLng(latitud,longitud );
                float zoomLevel = 14;
                mMarcadorCliente = googleMap.addMarker(new MarkerOptions().position(ubicacion).title("este es el cliente"));
                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ubicacion, zoomLevel));

                mLongitudCliente=longitud;
                mLatitudCliente=latitud;

            }
        });










    }



    public void posicionActual() {
        LocationManager mng = (LocationManager) getContext().getSystemService(getContext().LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location1 = mng.getLastKnownLocation(mng.getBestProvider(new Criteria(), false));
        mLatitud =  location1.getLatitude();
        mLongitud = location1.getLongitude();

    }


    @Override
    public void onResume() {
        super.onResume();

        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                    getFragmentManager().popBackStack();
                    return true;
                }
                return false;
            }
        });
    }
}

第一个抽屉选项片段:

public class OpcionDrawerUsuario extends Fragment {
    private TextView nombre;
    private TextView pass;
    private Button guardar;
    private Button salir;
    private FragmentoPrincipalChofer hilo=new FragmentoPrincipalChofer();

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

        //conseguir usuario actual
        // mUsuarioActual = ParseUser.getCurrentUser();


        View x = inflater.inflate(R.layout.opcion_drawer_usuario, container, false);
        nombre=(TextView)x.findViewById(R.id.nombreTv);
        pass=(TextView)x.findViewById(R.id.passTv);
        guardar=(Button)x.findViewById(R.id.guardarButtom);
        salir=(Button)x.findViewById(R.id.volverButtom);


        //cargar datos usuario


        ParseQuery<ParseUser> query = ParseUser.getQuery();
        query.whereEqualTo("username", "usuario1");
        query.findInBackground(new FindCallback<ParseUser>() {
            public void done(List<ParseUser> usuario, ParseException e) {
                if (e == null) {

                    nombre.setText(usuario.get(0).getUsername());



                } else {
                    // Something went wrong.
                }
            }
        });


        guardar.setOnClickListener(new View.OnClickListener() {
            @Override
         public void onClick(View v) {

            }
        });


        // Inflate the layout for this fragment
        return x;

    }

    @Override
    public void onResume() {
        super.onResume();

        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                    getFragmentManager().popBackStack();
                    return true;
                }
                return false;
            }
        });
    }

}

1 个答案:

答案 0 :(得分:0)

我用以下方法解决了这个问题:

if (mView != null) {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null)
                parent.removeView(mView);
        }
        try {

 } catch (InflateException e) {
            e.printStackTrace();
        }