Using the hardware "back" button on Android

This lesson will show you how to handle the user pressing the hardware "back" button on an Android device.

You can download the sample stack from this url: https://tinyurl.com/y6uhx3vx

The backKey message

Android devices have a built in "back" button. LiveCode allows you to support the use of this button within your application by sending a backKey message to the current card.

If you do not pass or handle this message the engine will automatically quit.

Sample stack

Sample stack

Our example stack is simply a stack with 3 cards and 2 buttons that allow you to navigate between them. The "next" button goes to the next card and the "previous" button goes to the previous card.

Adding in support for the "back" button

Adding in support for the "back" button

In this stack we want the hardware "back" button to do the same as the "previous" button, unless we are on the first card, in that case we want the application to quit.

All we need to do is add a backKey message to our stack script that checks what card we are on and takes the appropriate action.

on backKey
   if the number of this card is 1 then
      pass backKey
   else
      go to the previous card
   end if
end backKey

3 Comments

Will Cate

Some times the previously viewed card isn't necessarily the "previous" card in the stack sequence. To handle that situation, add this code to the card's CloseCard handler:

global actualPrevCardNum
put the number of this cd into actualPrevCardNum

Then, the code of the backKey handler is:

global actualPrevCardNum
go cd actualPrevCardNum

Bao

Hi Will Cate, your problem can be solved by using the resent function in any of the following ways:
If I want the backkey to return to the previous card, I only put that card
on backkey
go to resent cd
end backkey

Bao

ups is recent not resent :(

Add your comment

E-Mail me when someone replies to this comment