How to handle back button in activity

How to handle a back button in an activity. Where I have some buttons. If I click one of the button it's redirecting to the buttons which I required. It's working fine but When I press back button it gets finished.

How to solve this problem. I have only one activity for all those buttons. Thanks in advance.

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) 
   {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) 
        {
            return false; //I have tried here true also
        }
        return super.onKeyDown(keyCode, event);
   }

I have used above code to handle back button but its not working. When I press back button its struck there itself.


You can handle it like this:

for API level 5 and greater

@Override
public void onBackPressed() {
    // your code.
}

older than API 5

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // your code
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

In addition to the above I personally recommend

onKeyUp():

Programatically Speaking keydown will fire when the user depresses a key initially but It will repeat while the user keeps the key depressed.*

This remains true for all development platforms.

Google development suggested that if you are intercepting the BACK button in a view you should track the KeyEvent with starttracking on keydown then invoke with keyup.

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK
            && event.getRepeatCount() == 0) {
        event.startTracking();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
            && !event.isCanceled()) {
        // *** Your Code ***
        return true;
    }
    return super.onKeyUp(keyCode, event);
}

For both hardware device back button and soft home (back) button eg " <- " this is what works for me. (*Note I have an app bar / toolbar in the activity)

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            //finish();
            onBackPressed();
            break;
    }
    return true;
}



@Override
public void onBackPressed() {
   //Execute your code here
   finish();

}

Cheers!

链接地址: http://www.djcxy.com/p/31898.html

上一篇: onSaveInstanceState在Android中单击后退按钮时

下一篇: 如何处理活动中的后退按钮