vikash singh
vikash singh

Reputation: 141

Can we limit the number of character in edittext of SearchView in Android?

Is there any api to set the limit no. of characters in SearchView ?

Upvotes: 12

Views: 6999

Answers (5)

Uuu Uuu
Uuu Uuu

Reputation: 1282

I am using the following code snippet in case R.id.search_src_text unresolved:

val searchEdt = searchView.findViewById<EditText>(androidx.appcompat.R.id.search_src_text)
searchEdt.filters = arrayOf(InputFilter.LengthFilter(10))

Upvotes: 0

deepa
deepa

Reputation: 2494

In XML layout try this..

 android:maxLength="20" //20 is number of characters.

Upvotes: -5

Alexei Volkov
Alexei Volkov

Reputation: 859

I am using following code snippet:

TextView et = (TextView) searchView.findViewById(R.id.search_src_text);
        et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});

Upvotes: 13

Alexander Zhak
Alexander Zhak

Reputation: 9272

EditText et = (EditText)searchView.findViewById(searchView.getContext().getResources()
            .getIdentifier("android:id/search_src_text", null, null));
    et.setFilters(new InputFilter[] { new InputFilter.LengthFilter({max_text_length}) });

Upvotes: 7

himb2001
himb2001

Reputation: 1361

Use this code it will do search only if length is less or equal to 5.You can make it change accordingly like returning true from onQueryTextChange() when text>5.

    final SearchView searchView = (SearchView) mSearchMenuItem.getActionView();     
          searchView.setSearchableInfo(searchManager.getSearchableInfo(mActivity.getSearchComponentName()));
          searchView.setIconifiedByDefault(true);
          searchView.setSubmitButtonEnabled(true);
          searchView.setOnQueryTextListener(new OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String arg0) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean onQueryTextChange(String arg0) {
                if(arg0.length()>5){
                    System.out.println("Text character is more than 5");
                    searchView.setQuery(arg0.substring(0,5), false);
                }
                return false;
            }
        });

Upvotes: 7

Related Questions