0

I want to make something happen on text selection, which is OnLongClickListener, but inside of that I need to get selected text, which is handled by default OnLongClickListener (at least I think it is). Actual result, by adding just my listener, is that my method is called, I'm trying to get indices of selection bounds, but these are 0. I can also see in debugger, that no text is selected in that momment.

Code:

textView.setTextIsSelectable(true);
textView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            int start = textView.getSelectionStart();
            int end = textView.getSelectionEnd();
            // the rest of code
        }
    }
}

Question: How can I preserve default listener, which will be called first and make selection and then call my function.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Possible duplicate of [How to set up a listener on the selected text in TextView](https://stackoverflow.com/questions/15091019/how-to-set-up-a-listener-on-the-selected-text-in-textview) – Remy Lebeau Dec 04 '17 at 23:34

1 Answers1

0

I think you misunderstand how listeners work. They don't replace standard behavior, so there is no default listener to invoke to make sure something happens.

In this case, most likely your OnLongClick listener is simply being called before the TextView has actually updated its selection. In which case, you can try having your listener delay its processing until after the selection is set. Look at using Handler.postDelayed() or AsyncTask for that purpose. For example:

textView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            new Handler().post(() -> {/*your code here*/});
        }
    }
}

But, that being said, OnLongClickListener is not the correct listener to use for text selection changes. You need an ActionMode Callback instead:

How to set up a listener on the selected text in TextView

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770