Search code examples
androidandroid-edittextinitializationlistenerselection

How to determine when EditText has completed its initialization?


I have a custom EditText where I override onSelectionChange to notify to observers when cursor position has changed. There is a little delay to prevent notifying too often when selection is changing rapidly (backpressure).

private static final long POST_SELECTION_CHANGED_DELAY = 500;

private Runnable mSelectionRunnable = new Runnable() {
   @Override
   public void run() {
      if (mSelectionListener != null) {
         mSelectionListener.onSelectionChanged();
      }
   }
};

@Override
protected void onSelectionChanged(int selStart, int selEnd) {
   super.onSelectionChanged(selStart, selEnd);
   postSelectionChanged();
}

private void postSelectionChanged() {
   removeCallbacks(mSelectionRunnable);
   postDelayed(mSelectionRunnable, POST_SELECTION_CHANGED_DELAY);
}

The problem is that during EditText initialization phase onSelectionChanged is raised at least once and that notifies my observers even if it's not already needed. I tried attaching listeners after a 1s delay, but that seems hacky to me.

So, is there a way to know when EditText initialization has completed so I can attach my listeners there? I already tried onAttachedToWindow but it's too early.


Solution

  • Maybe override onFocusChanged method?

    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {}
    

    So you can detect if EditText is focused and then proceed with your custom logic