B4J Question How To Honor DRY for Exit-by-Escape-key Functionality

cklester

Well-Known Member
Licensed User
I'm violating DRY by using this code in every single B4XPage class:

B4X:
Public Sub AddEscapeExit(ctl As Object)
    'allow Escape key to exit signin screen
    Dim r As Reflector
    r.Target = ctl
    r.AddEventFilter("keypressed","javafx.scene.input.KeyEvent.KEY_PRESSED")
End Sub

Sub KeyPressed_Filter (e As Event)
    Dim jo As JavaObject = e
    Dim keycode As String = jo.RunMethod("getCode", Null)
    If keycode = "ESCAPE" Then
        B4XPages.ClosePage(Me)
        e.Consume
    End If
End Sub

Everybody knows that violating DRY is a code-smell, so I'm asking, how do I generalize this algorithm so I can call it like this from every B4XPage class:

B4X:
Sub Main
    ...
    App.AddEscapeExit( myControl )
    ...
End Sub

In App.bas:

B4X:
Public Sub AddEscapeExit(ctl As Object)
    'allow Escape key to exit signin screen
    Dim r As Reflector
    r.Target = ctl
    r.AddEventFilter("keypressed","javafx.scene.input.KeyEvent.KEY_PRESSED")
End Sub

Sub KeyPressed_Filter (e As Event)
    Dim jo As JavaObject = e
    Dim keycode As String = jo.RunMethod("getCode", Null)
    If keycode = "ESCAPE" Then
        B4XPages.ClosePage(Me)
        e.Consume
    End If
End Sub

...but this does not work, probably because of the "B4XPages.ClosePage(Me)," as "Me" isn't accurate in the App class.

What do I do to generalize this functionality? Or should I bother? I have less than 10 pages, but if I ever want to upgrade the key event processing...

Maybe Event has the info I need. I'll check. But if anybody has an idea, please let me know.
 

TILogistic

Expert
Licensed User
Longtime User
There are several ways to do it.
What you have, now on each page, you can detect the keyboard (see log), using a class.
it's just a demo.

Note:
Configure the login page, without resizing.
 

Attachments

  • signin_test2.zip
    5.8 KB · Views: 171
Upvote 0
Top