简体   繁体   中英

How can I ignore leading spaces in my searchview?

In a normal Edittext I would use something like, in my TextWatcher method:

@Override
public void onTextChanged(CharSequence charSequence, int start, int before,
                          int count) {

  String str = charSequence.toString();
  //if it starts with " " then don't recognise it, simply put ""
  if (str.equals(" ")) {
    Edittext.setText("");
  }
}

How would I do the equivalent in my searchview ?

I am trying with things like:

   // listening to search query text change
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

  @Override
  public boolean onQueryTextChange(String query) {

        String str = searchView.getQuery().toString();
        //if it starts with " " then don't recognise it, make it ""
        if (str.equals(" ")) {
          searchView.setQuery("", false);

        }
      }
    });

Maybe

  @Override
  public boolean onQueryTextChange(String query) {

        String str = searchView.getQuery().toString().trim();
        //if it starts with " " then don't recognise it, make it ""
        if (str.equals("")) { 
          searchView.setQuery("", false);

        }
      }
    });

SearchView is a LinearLayout, so find inside it an EditText and set textChangedListener:

    fun SearchView.ignoreLeadingWhiteSpaces(){
       findViewById<EditText>(androidx.appcompat.R.id.search_src_text).apply {
         doOnTextChanged { text, _, _, _ ->
            if(text?.startsWith(" ") == true) {
                setText(text?.trim())
            }
         }
       }
    }

call:

searchView.ignoreLeadingWhiteSpaces()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM