Move from one fragment to another

2

I would like to know how I can move from one fragment to another without having to mount both of them in the container, then my code.

Activity where the container is and call the first fragment: public class Home extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_inicio);

    FragmentManager manager = getSupportFragmentManager();
    manager.beginTransaction().add(R.id.ejemplo, new Reloj()).commit();
}

}

the fragment called, to which I want to pass second fragment but I mount the two in the container:

public class Watch extends Fragment {

private FButton sesion1;
private FButton sesion2;
String horaServr = "";
TextView txtCurrentTime;
TextView hora;
TextView empiezaJAVA;
int horas;
Videoss videoss;
@TargetApi(Build.VERSION_CODES.N)
public Reloj() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.fragment_reloj, container, false);
    sesion1 = (FButton)view.findViewById(R.id.botonXML);
    sesion2 = (FButton)view.findViewById(R.id.boton2XML);
     txtCurrentTime = (TextView)view.findViewById(R.id.hora);
     hora = (TextView)view.findViewById(R.id.hora2);
     empiezaJAVA = (TextView)view.findViewById(R.id.empieza);

    Servicios1 hiloconexion;
    String IP = "http://pasennova.esy.es/pausas_activas/juego";
    String LOGIN = IP + "/hora.php";
    hiloconexion = new Servicios1();
    String cadenallamada = LOGIN;
    hiloconexion.execute(cadenallamada, "2");

    return view;

}public class Servicios1 extends AsyncTask<String,Void,String> {
    String evaluar ="";
    @Override
    protected String doInBackground(String... params) {
        String cadena = params[0];
        URL url = null;
        String devuelve = "";
        if (params[1].equals("2"))//Entrar
        {
            try
            {
                evaluar="2";
                url = new URL(cadena);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("User-Agent", "Mozilla/5.0" + " (Linux; Android 5.1; es-ES) Ejemplo HTTP");
                int respuesta = connection.getResponseCode();
                StringBuilder result = new StringBuilder();
                if (respuesta == HttpURLConnection.HTTP_OK)
                {
                    InputStream in = new BufferedInputStream(connection.getInputStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    String line;
                    while ((line = reader.readLine()) != null)
                    {
                        result.append(line);
                    }
                    JSONObject respuestaJSON = new JSONObject(result.toString());
                    String resultJSON = respuestaJSON.getString("estado");
                    devuelve = devuelve + resultJSON;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return devuelve;
        }
        return devuelve;
    }
    @Override
    protected void onCancelled(String s) {
        super.onCancelled(s);
    }
    @Override
    protected void onPostExecute(String s) {
        horaServr = s;
        if (horaServr.equals(""))
        {
            Toast.makeText(getActivity(),"Error de conexion"+s,Toast.LENGTH_LONG).show();
        }
        else
        if (horaServr.equals(null))
        {
            Toast.makeText(getActivity(),"Error de conexion"+s,Toast.LENGTH_LONG).show();
        }
        else {
            Thread myThread = null;
            Runnable runnable = new CountDownRunner();
            myThread = new Thread(runnable);
            myThread.start();
        }
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}

public void doWork() {
    getActivity().runOnUiThread(new Runnable() {
        @TargetApi(Build.VERSION_CODES.N)
        public void run() {
            try {


                sesion1.setEnabled(false);
                sesion2.setEnabled(false);
                Calendar c = Calendar.getInstance();
                int segundos = c.get(Calendar.SECOND);
                int minutos = c.get(Calendar.MINUTE);
                int horas = c.get(Calendar.HOUR);
                Date dt = new Date();
                int horas2 = dt.getHours();
                int minutos2 = dt.getMinutes();
                int segundos2 = dt.getSeconds();
                String curTime = horas2 + ":" + minutos2 + ":" + segundos2;
                hora.setText(curTime);
                String horaTelefono = String.valueOf(horas);
                if (horaServr.equals(horaTelefono)) {
                    if (horas2 < 12) {
                        String tiempo = horas + ":" + minutos + ":" + segundos+" AM";
                        txtCurrentTime.setText(tiempo);
                        if (horas2 <= 10) {
                            if ((horas2 == 10) || (horas2 == 11) || (horas2 == 12)) {
                                sesion1.setEnabled(true);
                                empiezaJAVA.setText("La rutina de la mañana la puede realizar");
                                sesion1.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        videoss = new Videoss();
                                        FragmentManager fragmentManager2 = getFragmentManager();
                                        FragmentTransaction trans2 =fragmentManager2.beginTransaction();
                                        trans2.replace(R.id.ejemplo,videoss);
                                        trans2.commit();
                                    }
                                });
                            } else {
                                sesion1.setEnabled(false);
                                int horasFaltante = 9 - horas2;
                                int minutosFaltante = 60 - minutos2;
                                int segundosFaltante = 60 - segundos2;
                                //  Toast.makeText(MainActivity.this, , Toast.LENGTH_LONG).show();
                                empiezaJAVA.setText("su rutina empieza: " + horasFaltante + ":" + minutosFaltante + ":" + segundosFaltante);
                            }
                        }
                    } else {
                        String tiempo = horas + ":" + minutos + ":" + segundos+ " PM";
                        txtCurrentTime.setText(tiempo);
                        if ((horas2 == 16) || (horas2 == 17) || (horas2 == 18)) {
                            sesion2.setEnabled(true);
                            empiezaJAVA.setText("La rutina de la tarde la puede realizar");
                            sesion2.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    videoss = new Videoss();
                                   FragmentTransaction tras = getFragmentManager().beginTransaction();
                                    tras.replace(R.id.ejemplo, new Videoss());
                                    tras.commit();
                                }
                            });
                        } else {
                            sesion2.setEnabled(false);
                            int horasFaltante = (15 - horas2);
                            int minutosFaltante = (60 - minutos2);
                            int segundosFaltante = (60 - segundos2);
                            // Toast.makeText(MainActivity.this, "Rutnias empiza en: " + horasFaltante + ":" + minutosFaltante + ":" + segundosFaltante, Toast.LENGTH_LONG).show();
                            empiezaJAVA.setText("Rutnias empiza en: " + horasFaltante + ":" + minutosFaltante + ":" + segundosFaltante);
                        }
                    }
                }
                else {
                    empiezaJAVA.setText("Actualiza el reloj de tu movil");
                    sesion1.setEnabled(false);
                    sesion2.setEnabled(false);
                }
            }
            catch (Exception e) {}
        }
    });
}
class CountDownRunner implements Runnable{
    // @Override
    public void run() {
        while(!Thread.currentThread().isInterrupted()){
            try {
                doWork();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }catch(Exception e){
            }
        }
    }
}

}

    
asked by GOMEZ MUÑOZ BRAYAN 11.11.2016 в 18:53
source

3 answers

1

What you should do is use the function to replace this function as its name suggests it replaces instead of adding another fragment you could also add it to the backtack if you want. but with the replace should be enough in your case here an example:

 FragmentManager manager = getSupportFragmentManager();
 manager.beginTransaction().replace(R.id.ejemplo, new Reloj()).commit();

Remember that R.id.example is the id of your container of fragments so you should have a more descriptive name for it.

    
answered by 11.11.2016 / 19:51
source
3
  

the fragment called, to which I want to pass second fragment but I   Mount both in the container.

They are getting over because you are adding a fragment by means of the . add () and not a fragment replacement using . Replace () :

 FragmentManager manager = getSupportFragmentManager();
    manager.beginTransaction().add(R.id.ejemplo, new Reloj()).commit();

The solution is to ensure that you make the transaction of fragments in the same container, always using . replace () .

FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.contenedor, fragment).commit();

With this you would replace the fragment without problem!

    
answered by 11.11.2016 в 21:37
1
                Fragmento_a_donde_quieres_ir fragmento = new Fragmento_a_donde_quieres_ir();
                FragmentManager manejador = getSupportFragmentManager();
                manejador.beginTransaction().addToBackStack(null).replace(R.id.contenedor2, fragmento).commit();
    
answered by 13.11.2016 в 07:00