我想出了一個解決方案,我不知道它是否是最好的解決方案,但它似乎工作得很好。我所做的是創建了一個擴展ArrayAdapter的自定義適配器。在自定義適配器中,我覆蓋了getFilter並創建了自己的Filter類來覆蓋performFiltering。這將啓動一個新的線程,因此它不會中斷用戶界面。以下是一個準系統的例子。
MyActivity.java
public class MyActivity extends Activity {
private AutoCompleteTextView style;
@Override
public void onCreate(Bundle savedInstanceState) {
...
style = (AutoCompleteTextView) findViewById(R.id.style);
adapter = new AutoCompleteAdapter(this, android.R.layout.simple_dropdown_item_1line);
style.setAdapter(adapter);
}
}
AutoCompleteAdapter.java
public class AutoCompleteAdapter extends ArrayAdapter<Style> implements Filterable {
private ArrayList<Style> mData;
public AutoCompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
mData = new ArrayList<Style>();
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Style getItem(int index) {
return mData.get(index);
}
@Override
public Filter getFilter() {
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if(constraint != null) {
// A class that queries a web API, parses the data and returns an ArrayList<Style>
StyleFetcher fetcher = new StyleFetcher();
try {
mData = fetcher.retrieveResults(constraint.toString());
}
catch(Exception e) {
Log.e("myException", e.getMessage());
}
// Now assign the values and count to the FilterResults object
filterResults.values = mData;
filterResults.count = mData.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence contraint, FilterResults results) {
if(results != null && results.count > 0) {
notifyDataSetChanged();
}
else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}
}
一個了不起的鏈接,未來的觀衆:):HTTP://makovkastar.github。 io/blog/2014/04/12/android-autocompletetextview-with-suggestions-from-a-web-service/ – Tina 2015-12-26 09:39:59