I’m making my first android application, and when I press the back button it shuts down the app, instead of going back to the previous activity. Does anyone know how I can fix this??
Thanks
This is my “Hoofdscherm” page, from here you can go to the “Acties” page
package com.WNF;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
public class Hoofdscherm extends Activity {
// aanroepen van een bundle, kan je elke naam geven die je maar wilt,
//zolang de bundle als de onCreate maar dezelfde naam hebben
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// de setContentView is niets meer dan de gegevens van de
//View ophalen uit de R.layout.naamvandeXML
// Onthoud goed dat je dezelfde XMLs voor meerdere pagina's
//kan gebruiken.
setContentView(R.layout.hoofdscherm);
Button b = (Button) findViewById(R.id.button1);
ImageButton i = (ImageButton) findViewById(R.id.imageButton1);
b.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Intent in = new Intent(Hoofdscherm.this,Acties.class);
startActivity(in);
finish(); //deze activity wordt gestopt
}
});
i.setOnClickListener(new OnClickListener(){
public void onClick(View g){
Intent ib = new Intent(Hoofdscherm.this,Acties.class);
startActivity(ib);
finish();
}
});
}
}
And this is the “Acties” page
package com.WNF;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
public class Acties extends Activity{
// aanroepen van een bundle, kan je elke naam geven die je maar wilt,
//zolang de bundle als de onCreate maar dezelfde naam hebben
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// de setContentView is niets meer dan de gegevens van de
//View ophalen uit de R.layout.naamvandeXML
// Onthoud goed dat je dezelfde XMLs voor meerdere pagina's
//kan gebruiken.
setContentView(R.layout.acties1);
getIntent();
}
}
From your
HoofdschermActivity you call yourActiesActivity. And then inActiesyou press back and your application closes. Right?What is happening is, ideally, from
Actieswhen you press back, it should go toHoofdscherm, but since you are callingfinish();in yourHoofdschermActivity, it no longer exists. Hence your application exits.If you want to go back to
HoofdschermfromActies, remove thefinish()call in yourHoofdschermActivity.EDIT:
Here’s a bit more about
finish().Remember – only call
finish()when you want to close your Activity, if you want to go back to it,don’t callfinish().