How to find text in android through a SearchView o

2019-09-11 12:57发布

I'm new in Android and I am making an application that has a TextView with a very long string, and I want the user to be able to search for particular word within the TextView through a SearchView or EditText. I know it's possible because I saw it in some applications, but can't find any examples on how to do it. I read something about textwatcher, but not how to do it. What I want is to work as Ctrl + F: find the written word and that the app select it. Something like this:

enter image description here

1条回答
放我归山
2楼-- · 2019-09-11 13:24

Well will you clearify how you wanted to search the text? do you just want to find it that is there or not? and in addition do you want to search by entering each letter in the EditText?

if you just want to do the both above the trick is like below:

boolean hasText=false;
editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (count > 0 && (s.charAt(0) != '1')) {
               hasText=textView.getText().toString().contains(s.toString());
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

By checking the hasText true or false you will no is it there or not.

查看更多
登录 后发表回答