Android: Volver a la actividad anterior


Quiero hacer algo simple en la aplicación de Android. ¿Cómo es posible volver a una actividad anterior.

¿Qué código necesito para volver a la actividad anterior

Author: Swati Garg, 2010-10-28

22 answers

Las actividades de Android se almacenan en la pila de actividades. Volver a una actividad anterior puede significar dos cosas.

  1. Ha abierto la nueva actividad desde otra actividad con startActivityForResult. En ese caso, puedes llamar a la función finishActivity () desde tu código y te llevará de vuelta a la actividad anterior.

  2. Mantenga un registro de la pila de actividad. Cada vez que inicie una nueva actividad con una intent, puede especificar una bandera de intención como FLAG_ACTIVITY_REORDER_TO_FRONT o FLAG_ACTIVITY_PREVIOUS_IS_TOP. Puede usar esto para barajar entre las actividades de su aplicación. Aunque no las he usado mucho. Echa un vistazo a las banderas aquí: http://developer.android.com/reference/android/content/Intent.html

Como se mencionó en los comentarios, si la actividad se abre con startActivity() entonces se puede cerrar con finish(). Si desea utilizar el botón Arriba, puede atraparlo en el método onOptionsSelected(MenuItem item) verificando el ID del elemento con android.R.id.home a diferencia de R.id.home como mencionado en los comentarios.

 428
Author: Abhinav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-25 19:15:29

Intente Activity#finish(). Esto es más o menos lo que el botón atrás hace por defecto.

 206
Author: adamp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-27 23:47:40

Simplemente escriba en click finish(). Te llevará a la Actividad anterior.

 68
Author: Umer Rana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-16 09:51:14

Solo esto

super.onBackPressed();
 62
Author: AtanuCSE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-18 06:55:57
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Esto le llevará a una actividad anterior manteniendo su pila y borrando todas las actividades posteriores de la pila.

Por ejemplo, si stack era A->B->C->D y comienzas B con esta bandera, stack será A - >B

 28
Author: Dmitry Ryadnenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-22 12:41:56

¿Quieres tomar el control del comportamiento del botón atrás? Puede anular el botón atrás (para ir a una actividad específica) a través de uno de dos métodos.

Para Android 1.6 y versiones anteriores:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        // do something on back.
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

O si solo es compatible con Android 2.0 o superior:

@Override
public void onBackPressed() {
    // do something on back.
    return;
}

Para más detalles: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html

 19
Author: Bryan Denny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-27 23:41:27

Simplemente llame a estos métodos para finalizar la actividad actual o volver por onBackPressed

finish();

O

onBackPressed();
 16
Author: Akshay Paliwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-04 09:32:50

Si ha configurado correctamente el AndroidManifest.archivo xml con actividad padre, puede utilizar:

NavUtils.navigateUpFromSameTask(this);

Donde esta es su actividad infantil.

 10
Author: Thomas Decaux,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-27 12:23:19

Si quieres ir a solo quieres ir a la actividad anterior usa

finish();

O

onBackPressed();

Si desea ir a la segunda actividad o por debajo de esa use lo siguiente:

intent = new Intent(MyFourthActivity.this , MySecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Bundle is optional
Bundle bundle = new Bundle();
bundle.putString("MyValue1", val1);
intent.putExtras(bundle);
//end Bundle
startActivity(intent);
 10
Author: Ram G.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-30 21:27:43

Agregue esto en su método onCLick (), volverá a su actividad anterior

Finish ();

O puedes usar esto. Funcionó perfectamente para mí

 @Override
  public boolean onOptionsItemSelected(MenuItem item) {
  int id = item.getItemId();

      if ( id == android.R.id.home ) {
         finish();
         return true;
       }

  return super.onOptionsItemSelected(item);
  }
 8
Author: Darshuu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-21 05:28:46

Puede llamar explícitamente onBackPressed es la forma más fácil
Refiérase Vuelva a la actividad anterior para más detalles

 6
Author: Labeeb Panampullan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-13 15:16:54

Inicia la segunda actividad usando intent (usa startActivity o startActivityForResult según tus requisitos). Ahora cuando el usuario presione el botón atrás, la actividad actual en la parte superior se cerrará y se mostrará la anterior.

Ahora digamos que tiene dos actividades, una para seleccionar algunos ajustes para el usuario, como idioma, país, etc., y después de seleccionarlo, el usuario hace clic en el botón Siguiente para ir al formulario de inicio de sesión (por ejemplo) . Ahora, si el inicio de sesión no tiene éxito, el usuario estará en el actividad de inicio de sesión, ¿qué pasa si el inicio de sesión es exitoso ?

Si el inicio de sesión es exitoso, entonces usted tiene que iniciar otra actividad. Esto significa que se iniciará una tercera actividad, y todavía hay dos actividades en marcha. En este caso, será bueno usar startActivityForResult. Cuando el inicio de sesión se realice correctamente, envíe los datos OK a la primera actividad y cierre la actividad de inicio de sesión. Ahora, cuando se reciban los datos, inicie la tercera actividad y cierre la primera actividad usando finish.

 5
Author: Altaf Hussain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-05 18:11:02

Tiene el mismo problema y

finish();  OR super.onBackPressed();

Funcionó bien para mí, ambos funcionaron igual, pero no hubo suerte con return

 5
Author: NoNaMe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-30 04:24:35

Puedes probar esto:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

        finish();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
 4
Author: nikki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-31 10:16:29
@Override
public void onBackPressed() {
    super.onBackPressed();
}

Y si desea en el botón haga clic en volver a continuación, simplemente poner

bbsubmit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        onBackPressed();
    }
});
 4
Author: Md Hussain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-25 20:12:26

Prueba esto es actuar como usted tiene que presionar el botón atrás

finish();
onBackPressed();
 4
Author: Muhammed Fasil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-08 15:49:15

Todas las nuevas actividades/intentos por defecto tienen un comportamiento atrás/anterior, a menos que haya codificado un finish() en la actividad que llama.

 3
Author: ameyx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-07 17:38:41

Sugiero la NavUtils.navigateUpFromSameTask (), es fácil y muy simple, puedes aprenderlo del desarrollador de Google.Ojalá pudiera ayudarte!

 1
Author: wuxue,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-10 14:26:05

Además de todas las respuestas mencionadas, su todavía es una forma alternativa de hacer esto, digamos que tiene dos clases, clase A y clase B.

Clase A ha realizado algunas actividades como seleccionar casilla de verificación, imprimió algunos datos e intent a clase B. Clase B, le gustaría pasar varios valores a la clase A y mantener el estado anterior de la clase A, puede usar, probar este método alternativo o descargar código fuente para demostrar esto

Http://whats-online.info/science-and-tutorials/125/Android-maintain-the-previous-state-of-activity-on-intent/

O

Http://developer.android.com/reference/android/content/Intent.html

 0
Author: Daniel Nyamasyo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-30 05:24:25
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
      int id = item.getItemId();

      if ( id == android.R.id.home ) {
          finish();
          return true;
      }

      return super.onOptionsItemSelected(item);
 }

Prueba esto funciona tanto en barra de herramientas botón atráscomo hardware botón atrás.

 0
Author: Puni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-30 14:23:49

Solo prueba esto en, primera actividad

Intent mainIntent = new Intent(Activity1.this, Activity2.class);
this.startActivity(mainIntent);

En su segunda actividad

@Override
public void onBackPressed() {
    this.finish();
}
 0
Author: byteC0de,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-30 09:20:36

Hay pocos casos para volver a su actividad anterior:

Caso 1: si desea recuperar el resultado de su actividad anterior, entonces ActivityA.java

 Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
               startActivityForResult(intent,2);

Fbhelperactividad.java

 Intent returnIntent = new Intent();
 setResult(RESULT_OK, returnIntent);
 finish();

Caso 2: ActivityA --> FBHelperActivity---->ActivityA

ActivityA.java

 Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
               startActivity(intent);

Fbhelperactividad.java

after getting of result call finish();
 By this way your second activity will finish and because 
 you did not call finish() in your first activity then
 automatic first activity is in back ground, will visible.
 0
Author: Gyan Swaroop Awasthi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-30 13:45:39