开发者

Back Button to close app

I have a splash screen which leads into a main navigational screen which has animations in it to introduce the buttons. Want I want is to close the app when the back button is pressed. It currently reloads the activity (main) when the return button is called - why is this?

I looked about on the forums and one way was to use the finish() method. I tried implementing this in the main.java class like this:

public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if( keyCode == KeyEvent.KEYCODE_BACK ) 
    {     
        this.finish();

        return true;
    }
    return false;
}

But the above didn't do it - what am I doing wrong?

Cheers

UPDATE

Cheers all for swift reply but none of these works. But I think I may know why - my class only implements the onCreate() method and none others. Could this be why all the other methods are failing?

UPDATE

Hi - I sorted it but I don't, at this moment, understand why this works & the other methods don't work:

@Override
public boolean onKeyDown(int keyCode, KeyEve开发者_如何学Cnt event)  {
    if ( keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 ) 
    {
        // do something on back.
        moveTaskToBack( true );
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

So why would this work and the finish() method used in the onBackPressed() demonstrated by ekawas doesn't??


onBackPressed is probably getting the keydown event before your onKeyDown is.


If I were to do this, I would call from the splash screen activity a startActivityForResults. Return a boolean that tells the activity to quit, and then finish the base activity.


Make sure you call finish in the splash screen Activity after calling startActivity, then try this in your onKeyDown:

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

        return super.onKeyDown(keyCode, event);
    }


@overide
public void onBackPressed() {
   finish();
   return;
}

Do that in your activity rather than listening for key presses.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜