How to determine when text is selected [Android [E

2019-09-01 05:41发布

Is possible to determine when text is selected and when is not?

I was googling and I find onSelectionChanged() method or setOnLongClickListener() for determining when user longClicks the editText so when he made selection, but in both cases it can't help me with determining, when the user is not selecting any text (I could set button invisible)...

3条回答
迷人小祖宗
2楼-- · 2019-09-01 06:23

You can check editText.getSelectionStart() and editText.getSelectionEnd() and check if those values are:

  • the same: user did not select text
  • different: the user selected text

So:

int startSelection= textAbove.getSelectionStart();
int endSelection= textAbove.getSelectionEnd();

if (startSelection != endSelection) {
    ... DO SOMETHING ...
}
查看更多
Ridiculous、
3楼-- · 2019-09-01 06:26
int startSelection=et.getSelectionStart();
int endSelection=et.getSelectionEnd();  

The getSelectionStart() method will return the start of the selection anchor/cursor or -1 if the user has not selected any text. You could try using this.

查看更多
你好瞎i
4楼-- · 2019-09-01 06:30

You can use

yourEditText.setOnTouchListener(new View.OnTouchListener() {
          @Override
          public boolean onTouch(View v, MotionEvent event) {

            if (MotionEvent.ACTION_UP == event.getAction()) {

              if (yourEditText.hasSelection()) {
                // if true, the text in the EditText is selected
              }

            return false;
          }
        });


That should do it.

查看更多
登录 后发表回答