Activity_KeyPress ?

susu

Well-Known Member
Licensed User
Longtime User
Currently my App can be closed by 2 ways:

1. Tap menu Exit on screen.
2. Press back button on device.

But I only want to accept the "menu way" not "button way". I try to catch KeyPress event but I don't know how. Documentation doesn't mention about it too.
 

Cor

Active Member
Licensed User
Longtime User
Here is some example which i use

B4X:
Sub Activity_KeyPress (KeyCode As Int) As Boolean 'return true if you want to consume the event
    If KeyCode = KeyCodes.KEYCODE_BACK Then
       If panelSearch.Visible=True Then 
       panelSearch.Visible=False
       Return True
      End If 
   
        res = Msgbox2("Do you want to exit?", "", "Yes", "", "No", Null)
        If res = DialogResponse.NEGATIVE Then Return True
    End If
    Return False
End Sub
 
Upvote 0

susu

Well-Known Member
Licensed User
Longtime User
Thanks you guys so much.
 
Upvote 0

susu

Well-Known Member
Licensed User
Longtime User
I want activity ignores back button, home button and only close after user press menu button 3 times. My code below:

B4X:
Sub Globals
   Dim menucount As Int
End Sub

Sub Activity_Create(FirstTime As Boolean)
   menucount = 0
End Sub

Sub Activity_KeyPress (KeyCode As Int) As Boolean

    If Keycode = KeyCodes.KEYCODE_BACK Then
        Return True
    End If

    If Keycode = KeyCodes.KEYCODE_MENU Then
   Return True
    End If
    
    If Keycode = KeyCodes.KEYCODE_MENU Then
   menucount = menucount + 1
   If menucount = 3 Then
   Activity.Finish
   End If
    End If
   
End Sub

It compiled ok but it doesn't work as I want. It ignores back button not home button and nothing happen when I press menu button 3 times. Something's wrong here? :sign0085:
 
Upvote 0

klaus

Expert
Licensed User
Longtime User
If you look at your code!
In the 2nd and in the 3rd If statement you test the same KeyCode !
Replace your code by :
B4X:
Sub Activity_KeyPress (KeyCode As Int) As Boolean
 
    If Keycode = KeyCodes.KEYCODE_BACK Then
        Return True
    End If
 
    [COLOR=red]If Keycode = KeyCodes.KEYCODE_HOME[/COLOR] Then
    Return True
    End If
 
    If Keycode = KeyCodes.KEYCODE_MENU Then
    menucount = menucount + 1
    If menucount = 3 Then
    Activity.Finish
    End If
    End If
 
End Sub

Should work.

Best regatrds.
 
Upvote 0

susu

Well-Known Member
Licensed User
Longtime User
Thanks Erel, I can live with this "feature" :D
Thanks Klaus, it's my mistake. Now activity closed after press menu button 3 times. :D
 
Upvote 0
Top