質問

so I am new to android development and I am stuck with small problem. I got this code: `

Button button2=(Button)findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        startActivity(new Intent(Menu.this, pistols.class));
        finish();
    }

});`

That part is working fine, but when I start next Activity, and I want to return to previous activity using hardware device button(back button) it closes application instead of returing me to previous activity. What should I do?

役に立ちましたか?

解決 2

This one helps

Button button2=(Button)findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    startActivity(new Intent(Menu.this, pistols.class));

}});

another way around. you can override onBackPressed. start the first activity from there.

@Override
public void onBackPressed() {
    super.onBackPressed();
// call the first activity here
    this.finish();
}

他のヒント

Remove finish(). It should fix it, because you call `finish() it kills the activity and removes it from the back stack thus you can't return to it by pressing the back button.

Button button2=(Button)findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        startActivity(new Intent(Menu.this, pistols.class));

    }

});`

Remove finish

please search or do RnD about the activityforresult

in your code startactivity(...) will start the new activity and the very next line i.e finish() will finishes the current activity. so you cannot return to previous activity after you have pressed back button.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top