我需要在listview中搜索项目。我有简单的字符串和数组适配器数组,我在一些不同的问题及其工作中找到了代码!但是我有一个问题,这个搜索非常慢并且滞后于一个字母我有一个单词“arbuz”(其中一个是其中之一)而且我打印了一个 - 什么都没有,另外一个字母和单词搜索“a”,另一个 - 而且没有这样的单词。我希望你解开我。我怎么能改进这个搜索? 我的代码:
public class FragmentWithList extends ListFragment {
ListView mainList;
EditText inputSearch;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_with_list, null);
mainList = (ListView) v.findViewById(android.R.id.list);
inputSearch = (EditText)v.findViewById(R.id.inputSearch);
return v;
}
public void onCreate(Bundle savedInstanceState){
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String values[] = new String[]{"arbuz","abrikos","banan","cup","charlie","derevo","grusha","ogurets","sliva","jabloko","volk","dom","igra","pharaon","muscle"};
Comparator<String> ALPHABETICAL_ORDER1 = new Comparator<String>() {
public int compare(String object1, String object2) {
int res = String.CASE_INSENSITIVE_ORDER.compare(object1.toString(), object2.toString());
return res;
}
};
Collections.sort(Arrays.asList(values), ALPHABETICAL_ORDER1);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,values);
mainList.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
adapter.getFilter().filter(s.toString());
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
答案 0 :(得分:1)
在afterTextChanged()
方法
adapter.getFilter().filter(s.toString());