Tuesday, September 24, 2013

How to disable back button in Android

Android phones come with a back button to go to previous activity.



http://docs.xamarin.com/static/guides/android/application_fundamentals/activity_lifecycle/Images/image4.png


There can be workflows where you may not want to go to previous Activity unless certain action is completed.  Sometimes, the current workflow may be in unstable state.  Sometimes, going back may not make any sense in the workflow.

The simple way to avoid using back button is to implement

onBackPressed() event in the activity.

If you are using a old version of Android, you may have to override onKeyDown.

public boolean onKeyDown(int keyCode, KeyEvent event)

Just check for (keyCode == KeyEvent.KEYCODE_BACK).

-----

This leads to another button that may close the Application - the Home button.  Home button takes you to Android device home.  Should that be overridden too?

It is unwise to override Home button.  Instead of trying to handle Home button's press, the Application's workflow should be designed to handle Home button is press during its execution. Here is a www.stackoverflow.com discussion on this topic.

Happy coding

No comments:

Post a Comment