Android Question KeyPress Event

Guenter Becker

Active Member
Licensed User
Hello,
I like to use the activity keypress event in a b4xpages application. And I mean any keypress any char! I need a b4a/b4x code snipped how to setup the activity event (delagate) and how to setup the corresponding Listener/event/sub in the b4xpage been triggert by the activity event.
Can anyone help me?
 

aeric

Expert
Licensed User
You can find in Main Activity
B4X:
Sub Activity_KeyPress (KeyCode As Int) As Boolean
    Log(KeyCode)
    Return B4XPages.Delegate.Activity_KeyPress(KeyCode)
End Sub
 
Upvote 0

Guenter Becker

Active Member
Licensed User
Thank you I now that but in a post erel says that his is only for intercepting the back key. Also it is not shown how to set the appropriated sub event in the pages code
 
Upvote 0

Cableguy

Expert
Licensed User
B4XPages parent is, in most cases, the MainActivity... if your goal is to catch keypresses dedicated to a particular view, then you need to see if that view already exposes such event, or if not, create a listener to it (custom event). Such events are almost specific to Text views like TextView and such.
 
Upvote 0

William Lancee

Active Member
Licensed User
I took some time to experiment. It possible to have mastery over the soft keyboard and capture key presses for any page in B4XPages - even without an apparent target view! The IME has to be handled in Main Activity module. Here is my convoluted solution. There are likely much more elegant ways!

B4X:
'In Main Activity module
Sub Globals
    Private ime As IME
End Sub

Sub Activity_Create(FirstTime As Boolean)
    ime.Initialize("IME")
    Dim pm As B4XPagesManager
    pm.Initialize(Activity)
End Sub

Public Sub showKB(v As EditText)
    ime.ShowKeyboard(v)
End Sub

Public Sub hideKB
    ime.HideKeyboard
End Sub

B4X:
'In page where keycodes need to be captured.

Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
'    Root.LoadLayout("page2")
    Dim ghostView As EditText
    ghostView.Initialize("ghostView")
    Root.AddView(ghostView, 0, 0, 0, 0)
    
    Sleep(50)
    ghostView.RequestFocus
    CallSub2(Main, "showKB", ghostView)
    
    'if you want to hide the keyboard
    'CallSub(Main, "hideKB")
End Sub

Private Sub ghostView_TextChanged(old As String, new As String)
    Log(new.charAT(new.length-1))
End Sub
 
Upvote 0

Guenter Becker

Active Member
Licensed User
B4XPages parent is, in most cases, the MainActivity... if your goal is to catch keypresses dedicated to a particular view, then you need to see if that view already exposes such event, or if not, create a listener to it (custom event). Such events are almost specific to Text views like TextView and such.
Thank you, can you give me an code example for a listener. I know what a listener is but I never used it.
 
Upvote 0

Guenter Becker

Active Member
Licensed User
Upvote 0
Top