How to determine when text is selected [Android [EditText]]

大城市里の小女人 提交于 2019-12-13 06:53:58

问题


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)...


回答1:


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.




回答2:


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.




回答3:


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 ...
}


来源:https://stackoverflow.com/questions/27489788/how-to-determine-when-text-is-selected-android-edittext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!