EditText focus issue

kickaha

Well-Known Member
Licensed User
Longtime User
I was looking at a question on here and decided that the elegant solution was to have a variable that stored the current EditText that had focus.

So, I came up with the test code below:
B4X:
'Activity module
Sub Process_Globals
   'These global variables will be declared once when the application starts.
   'These variables can be accessed from all modules.

End Sub

Sub Globals
   'These global variables will be redeclared each time the activity is created.
   'These variables can only be accessed from this module.
   Dim Edit1 As EditText 
   Dim Edit2 As EditText 
   Dim CurrentEdit As EditText
End Sub

Sub Activity_Create(FirstTime As Boolean)

   Edit1.Initialize ("edit")
   Edit1.InputType = Edit1.INPUT_TYPE_NONE 
   Edit2.Initialize ("edit")
   Edit2.InputType = Edit2.INPUT_TYPE_NONE
   CurrentEdit = Edit2 ' Is this the offender? Remove it and things work as expected

   Activity.AddView (Edit1,10%x, 10%y, 80%x, 15%y)
   Activity.AddView (Edit2,10%x, 40%y, 80%x, 15%y)
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub edit_FocusChanged (HasFocus As Boolean)
   If HasFocus Then CurrentEdit = Sender
End Sub

I found that if CurrentEdit was set to one of the EditTexts, when you swap the focus between them (by tapping on the screen), the EditTexts eventually became the same - look at the code in debug with a breakpoint at line 37.

If you remove line 21 things work!

Is this a bug in B4A or a bug in my head?
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
You can fix this issue by changing Sub edit_FocusChanged to:
B4X:
Sub edit_FocusChanged (HasFocus As Boolean)
    Dim e As EditText
    e = Sender
    If HasFocus Then CurrentEdit = e
End Sub

I will try to explain why it happens.
All the views in Basic4android are defined as "wrappers". They wrap an internal object which is the native view in most cases. This is related to the difference between the Java model and Basic4android model.

If you assign an object of unknown type to a wrapper type then the internal object is replaced. Sender keyword returns such an unknown object. The actual value of Sender in this case is the native EditText (not the wrapper).

If you explicitly create a new EditText variable then the two types match and everything will work as expected.
 
Top