How to get handle on back-button events?

Put your problem here if it does not fit any of the other categories.

How to get handle on back-button events?

Postby ironchef » Thu Sep 09, 2010 4:16 pm

Hello androids!
Is there any way to "prevent" back-button from going to the previous activity from current activity? Or any way to even prompt a 'are you sure you want to ...' -confirmation? Thank you!
ironchef
Freshman
Freshman
 
Posts: 9
Joined: Mon May 10, 2010 11:09 am

Top

Re: How to get handle on back-button events?

Postby achie1266 » Thu Sep 09, 2010 5:42 pm

From your Activity you may override the onKeyDown method and handle the back button events.
Always return super.onKeyDown(keyCode, event) to let android take care of all other events that you do not handle.

When you handle a event you can tell the android that you have handled it by returning true. I am returning false in my snippet below.

Warning: the users expect the activity to be closed when they click on back button, So if you want to have another confirmation, then build a dialog or whatever and prompt them but make sure you give them an option to quit that activity. Or else your activity will be viewed as a malicious or improperly implemented one.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  public boolean onKeyDown(int keyCode, KeyEvent event) {
  2.         if (keyCode == KeyEvent.KEYCODE_BACK) {
  3.                 Toast.makeText(this, "Back Button Clicked", Toast.LENGTH_SHORT).show();
  4.                 return false;
  5.         }
  6.         return super.onKeyDown(keyCode, event);
  7.     }
Parsed in 0.032 seconds, using GeSHi 1.0.8.4
achie
User avatar
achie1266
Master Developer
Master Developer
 
Posts: 223
Joined: Mon Nov 09, 2009 10:56 pm
Location: Denver

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 17 guests