用于自动完成的自定义ArrayAdapter,显示所有结果

时间:2012-03-07 08:39:10

标签: android autocomplete android-arrayadapter

这是我的自定义ArrayAdapter

    public class CustomAdapater extends ArrayAdapter implements Filterable {
    private ArrayList<String> mData;
    private ArrayList<String> orig;
    private ArrayList<String> suggestions;
    LayoutInflater inflater;
    @SuppressWarnings("unchecked")
    public CustomAdapater(Context context, int textViewResourceId,ArrayList<String> al) {
        super(context,textViewResourceId,al);
        inflater = LayoutInflater.from(context);
        mData = al;
        orig = (ArrayList<String>)mData.clone();
        this.suggestions = new ArrayList<String>();
    }

    @Override
    public int getCount() {
        return suggestions.size();
    }

    @Override
    public Object getItem(int position) {
        return suggestions.get(position);
    }

    @Override
    public Filter getFilter() {
        Filter myFilter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();              
                if(constraint != null) {
                    suggestions.clear();
                    for(String s:orig){
                        if(s!=null && s.contains(constraint))
                        suggestions.add(s);
                    }
                    filterResults.values = suggestions;
                    filterResults.count = suggestions.size();
                }
                return filterResults;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence contraint, FilterResults results) {
                mData = (ArrayList<String>)results.values;
                notifyDataSetChanged();             
            }
        };
        return myFilter;
    }
}

我将此应用于自动填充字段。默认情况下,自动填充搜索列表以搜索字符串开头。我想要包含搜索字符串的列表。

1 个答案:

答案 0 :(得分:0)

对于你想要的功能,我认为你应该编写自己的代码..因为默认的自动完成字段是不可能的...... 假设这是您用于自动完成的字符串数组..

static final String[] COUNTRIES = new String[20];

它有20个国家..然后尝试这样搜索..

for(int i=0;i<20;i++)
{
int index=COUNTRIES[i].index(autocomplete.getText().toString);//<---- here autocomplete is the autocomplete textview
if (index >-1)
{
lst.add(COUNTRIES[i])<----- lst is the arraylist of strings you should create
}
}
runOnUiThread(new Runnable(){
 public void run() {
 for(int k=0;k<lst.size();k++)
 {
adapter.add(lst[k])
 }
 adapter.notifyDataSetChanged();
}
}
);

当autocomplete.getText()时,在另一个线程中运行此代码.length&gt; 1(或任何你想要的长度)......我想你会得到所需的结果.. =]