user836026
user836026

Reputation: 11350

Change ListView Filter to match start of string only

I have have an activity with listview showing list of countries and search box on the top.

I simply need to filter Listview based on inputed text.

using Filter it works fine. except it match the inputed string to any match on text ,either begin or in the middle, while I need only to match the start of string only.

for example, if user type "f", it display:

Burkina Faso Falkland Islands Faroe Islands Fiji Finland France

Now, "Burkina Faso", doesn't start with F, it just displayed because it contains F.

how could i change the filter to look only for start of string.

inputSearch = (EditText) findViewById(R.id.inputSearch);
        inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                CountryListViewActivity.this.adapter2.getFilter().filter(cs);  
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub                          
            }
        });

Upvotes: 0

Views: 443

Answers (1)

nickmartens1980
nickmartens1980

Reputation: 1593

In your listadapters filter implement the matching part of you filter method with something like

if (placeName.toLowerCase().startsWith(filterValue.toLowerCase()) {
    // add it to the result list
}

The current algorithm you are using is using contains.

Upvotes: 1

Related Questions