KEYCODE_BACK don't close activity

XverhelstX

Well-Known Member
Licensed User
Longtime User
Heey there,

yet another question.

How do you keep your activity alive when you press the back button?
Sub Activity_KeyPress (KeyCode As Int) As Boolean

If Keycode = KeyCodes.KEYCODE_BACK Then
//don't stop activity.
End If


End Sub

Thanks!

XverhelstX
 

kickaha

Well-Known Member
Licensed User
Longtime User
You need to "consume" the event
B4X:
Sub Activity_KeyPress (KeyCode As Int) As Boolean 'return true if you want to consume the event
   If KeyCode = KeyCodes.KEYCODE_BACK Then Return True
End Sub
 
Upvote 0

TomK

Member
Licensed User
Longtime User
This is how I would do it

B4X:
Sub Activity_KeyPress (KeyCode As Int) As Boolean 'return true if you want to consume the event
   Dim result As Int
   Dim bp As Bitmap
   bp.Initialize(File.DirAssets, "index.jpg")
   
   If KeyCode = 4 Then
      result = Msgbox2("Back hit, exit are you sure?", "App Title", "Yes", "Cancel", "No", bp)
      
      Select result
         Case -1 ' yes hit ie., exit the app
            Return False
         Case -3 ' cancel hit, do nothing really, and leave the app running
            Return True ' which consumes the event and doesnt exit
         Case Else
            Return True ' also does not exit because it consumes event
      End Select
            
   End If
End Sub
 
Upvote 0

kickaha

Well-Known Member
Licensed User
Longtime User
This is how I would do it

B4X:
Sub Activity_KeyPress (KeyCode As Int) As Boolean 'return true if you want to consume the event
   Dim result As Int
   Dim bp As Bitmap
   bp.Initialize(File.DirAssets, "index.jpg")
   
   If KeyCode = 4 Then
      result = Msgbox2("Back hit, exit are you sure?", "App Title", "Yes", "Cancel", "No", bp)
      
      Select result
         Case -1 ' yes hit ie., exit the app
            Return False
         Case -3 ' cancel hit, do nothing really, and leave the app running
            Return True ' which consumes the event and doesnt exit
         Case Else
            Return True ' also does not exit because it consumes event
      End Select
            
   End If
End Sub

Bit of a sledgehammer to crack a nut, it is simpler:
B4X:
Sub Activity_KeyPress (KeyCode As Int) As Boolean 'return true if you want to consume the event
   Dim result As Int
   Dim bp As Bitmap
   bp.Initialize(File.DirAssets, "index.jpg")
   
   If KeyCode = 4 Then
      result = Msgbox2("Back hit, exit are you sure?", "App Title", "Yes", "Cancel", "No", bp)
      If result = -1 Then' yes hit ie., exit the app
         Return False
      Else
         Return True ' which consumes the event and doesnt exit
      End If            
   End If
End Sub
I would also remove the "Cancel" button from the MsgBox
 
Upvote 0
Top