Android - AutoCompleteTextView wildcard suggestion

这一生的挚爱 提交于 2019-12-03 16:12:09

Okay here's how I made it work. Major props to pskink for the lead. It's very similar to the code I have above, with some changes to make the runQuery method work.

The same logic/thought pattern is used, only that I changed the runQuery method. Read the comments for a walkthrough.

//create ACTV Here
AutoCompleteTextView search = (AutoCompleteTextView) findViewById(R.id.actvCatalogueSearch);
search.setThreshold(1);

//I don't know what these are for, honestly.
String[] from = { "name" };
int[] to = { android.R.id.text1 };

//create a simple cursorAdapter
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, 
        android.R.layout.simple_dropdown_item_1line, null, from, to, 0);

//again, I don't know what this is for
cursorAdapter.setStringConversionColumn(1);

//create the filter query provider
FilterQueryProvider provider = new FilterQueryProvider(){
    @Override
    public Cursor runQuery(CharSequence constraint) {
        // TODO Auto-generated method stub
        //I need to do this because my list items are in all caps
        String constrain = (String) constraint;
        constrain = constrain.toUpperCase(); 

        if (constraint == null) {
            return null;
        }

        //I'll be honest again, no clue what these lines do. 
        String[] columnNames = { Columns._ID, "name" };
        MatrixCursor c = new MatrixCursor(columnNames);

        try {
            //here's what I do, I go though my Array (pdflist)
            //when a list item contains the user input, I add that to the Matrix Cursor
            //this matrix cursor will be returned and the contents will be displayed 
            for (int i = 0; i < pdflist.length; i++) {
                if(pdflist[i].contains(constrain)){
                    c.newRow().add(i).add(pdflist[i]);  
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c;
    }
};

//use the filter query provider on the cursor adapter
cursorAdapter.setFilterQueryProvider(provider);

//finally, use the adapter on your ACTV
search.setAdapter(cursorAdapter);

It's a bit of a work but it gets the job done. Honestly, I'm a bit surprised that there's no "straightforward/intuitive" way of doing this. Something to the tune of just enabling/disabling something in your AutoCompleteTextView then it's done.

I guess we'll have to stick with this solution until further notice.

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