Search code examples
javaandroidmemory-model

One-shot OnFocusChangeListener for an EditText on Android


I need to implement a one-shot OnFocusChangeListener for my EditText. I.e., once the EditText gets focus, it do something and stop listening for the focus change event.

I assign an ananymous OnFocusChangeListener to my EditText. Then in void onFocusChange(View v, boolean hasFocus) I call v.setOnFocusChangeListener(null);

It works, but I wonder why it's possible to null out the OnFocusChangeListener in its own method onFocusChange. I think I'm missing something from the Java memory model.

The code is below:

mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            // do something
            v.setOnFocusChangeListener(null);
        }
    }
});

Solution

  • Dont panic, you cant harm the object. There is protected OnFocusChangeListener mOnFocusChangeListener in the View object. Lets say it points to address 16 in your memory.

    You can assign new object to it, and it will start to point lets say , at address 29. But the function that runs is from object 16.

    Just the next time the OS gets that focus change, they will trigger the function at the object at memory 29, in a way this will be the last time you use this function for object at 16.

    What you do is pointing at null, instead of 29, it works the same. I hope I explained it somewhat well...