我创建了一个自定义ArrayAdapter
所以我可以将结果过滤到我的AutoCompleteTextView
:
public class AutoCompleteCountryAdapter extends ArrayAdapter<String>
{
private List<String> countryListFull;
public AutoCompleteCountryAdapter(@NonNull Context context, int resource, @NonNull List<String> countryList)
{
super(context, resource, countryList);
countryListFull = new ArrayList<>(countryList);
}
@NonNull
@Override
public Filter getFilter()
{
return countryFilter;
}
private Filter countryFilter = new Filter()
{
@Override
protected FilterResults performFiltering(CharSequence constraint)
{
FilterResults filterResults = new FilterResults();
List<String> suggestions = new ArrayList<>();
if (constraint == null || constraint.length() == 0)
{
suggestions.addAll(countryListFull);
} else
{
String filterPattern = constraint.toString().toLowerCase().trim();
for (String country : countryListFull)
{
if (country.toLowerCase().startsWith(filterPattern))
{
suggestions.add(country);
}
}
}
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults)
{
clear();
addAll((List) filterResults.values);
notifyDataSetChanged();
}
@Override
public CharSequence convertResultToString(Object resultValue)
{
return ((String) resultValue);
}
};
}
但是,当我尝试使用此适配器时:
List<String> placeOfBirthList;
AutoCompleteCountryAdapter pobAdapter = new AutoCompleteCountryAdapter(new AutoCompleteCountryAdapter(getApplication().getApplicationContext(), android.R.layout.simple_dropdown_item_1line, placeOfBirthList));
我收到此Logcat错误:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
我在创建新Filter后第一个花括号的行中得到此异常:
private Filter countryFilter = new Filter()
{ // HERE
我不是从我的MainActivity.java
中调用这个,而是从ViewModel
中的一种常规方法中调用不同活动的Fragment
。
public class MyViewModel extends AndroidViewModel {
private List<String> placeOfBirthList;
public MyViewModel(Application application) {
super(application);
myMethod();
}
private void myMethod() {
AutoCompleteCountryAdapter myAdapter = new AutoCompleteCountryAdapter(getApplication().getApplicationContext(), android.R.layout.simple_dropdown_item_1line, placeOfBirthList);
}
}
所以......我解决了这个问题。在一位同事的建议下,我将自定义ArrayAdapter的创建移动到了我的View片段中:
FragmentBinding binding = ~~~;
MyViewModel mViewModel = ~~~;
binding.setViewModel(mViewModel);
AutoCompleteCountryAdapter myAdapter = new AutoCompleteCountryAdapter(getContext(), android.R.layout.simple_dropdown_item_1line, viewModel.getPlaceOfBirthList());
binding.placeOfBirthField.setAdapter(myAdapter);
这解决了我所有的Looper问题。另外,它满足MVVM中“视图模型中没有视图代码”的要求。