android autocompletetextview should show only relevant options in drop down

半世苍凉 提交于 2019-12-22 11:07:43

问题


I am using a AutoCompleteTextView in my code and loading the list from database using SimpleCursorAdapter.

AutoCompleteTextView cocktailIngredientView = (AutoCompleteTextView) findViewById(R.id.item);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_spinner_item, mCursor,
                new String[] { "field" },
                new int[] { android.R.id.text1 });
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cocktailIngredientView.setAdapter(adapter);
cocktailIngredientView.setThreshold(0);

It populates the list correctly but i have two issues: 1. I want this list to be sorted 2. Whatever I enter, it is displaying the complete list. I want it to filter based on matching patterns in the list. e.g. if the list contains values Page, Tools...then if i enter T in the box, the drop down should show only Tools. The idea is to display options which contain the entered pattern anywhere in the string text.

How can this be done? Please help.

Regards, Sapan


回答1:


You have to tell the adapter what items to display. I tried implementing something similar to this by using a FilterQueryProvider that queries the database for the items that I want to display in the dropdown.

FilterQueryProvider filter = new FilterQueryProvider() {

    @Override
    public Cursor runQuery(CharSequence constraint) {
        // Make a DB query that filters based on the constraint

        return //whatever query results;
    }
};
myAdapter.setFilterQueryProvider(filter);

As for the situation when you select an item on the list, you have to override the CursorToStringConverter of the SimpleCursorAdapter. Something like:

SimpleCursorAdapter.CursorToStringConverter conv = new SimpleCursorAdapter.CursorToStringConverter() {

    @Override
    public CharSequence convertToString(Cursor cursor) {
        int numCol = cursor.getColumnIndexOrThrow("whateverFieldYouNeed");
        String term = cursor.getString(numCol);
        return term;
    }
};
myAdapter.setCursorToStringConverter(conv);



回答2:


Instead of the CursorToStringConverter you could also use

mAdapter.setStringConversionColumn(mCursor.getColumnIndexOrThrow("whateverFieldYouNeed"));


来源:https://stackoverflow.com/questions/5685626/android-autocompletetextview-should-show-only-relevant-options-in-drop-down

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