我正在使用带有自定义适配器的AutoCompleteTextView,但适配器似乎没有做任何事情。当我输入几个字母时,下拉列表不会显示。我将一些随机单词的ArrayList插入适配器。我还确保我实际上将适配器设置为textview,但没有任何反应。当我使用ArrayAdapter时,它起作用了。有人能告诉我我的代码有什么问题以及如何修复它?提前谢谢!
这是我的适配器
package com.chappota.weather.list.model;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Pranav on 11/10/2014.
*/
public class CityDropDownAdapter extends BaseAdapter implements Filterable {
ArrayList<String> mList;
Context mContext;
public CityDropDownAdapter(Context ctx, ArrayList<String> list) {
mList = list;
mContext = ctx;
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View mView = convertView;
if (mView == null) {
LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(android.R.layout.simple_dropdown_item_1line, null);
}
TextView suggestion = (TextView) mView.findViewById(android.R.id.text1);
suggestion.setText(mList.get(position));
suggestion.setTextColor(Color.BLACK);
return mView;
}
@Override
public Filter getFilter() {
return new CityFilter();
}
private class CityFilter extends Filter {
@Override
public String convertResultToString(Object resultValue) {
return (resultValue.toString());
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
ArrayList<String> mData = mList;
ArrayList<String> mSuggestions = mList;
mSuggestions.clear();
//Check for similarities in data from constraint
for (String value : mData) {
if (value.toLowerCase().contains(constraint.toString().toLowerCase())) {
mSuggestions.add(value);
Toast.makeText(mContext, value + " contains " + constraint.toString(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext, value + " does not " + constraint.toString(), Toast.LENGTH_LONG).show();
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = mSuggestions;
filterResults.count = mSuggestions.size();
return filterResults;
} else {
return null;
}
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
}
}
}
}
有人可以告诉我我做错了什么,以及我该如何解决?在此先感谢!
答案 0 :(得分:0)
你在这里提供参考,
ArrayList<String> mData = mList;
ArrayList<String> mSuggestions = mList;
然后清除它,
mSuggestions.clear();
这就是为什么循环没有数据而且无法正常工作的原因。
而是声明新对象,就像这样,
ArrayList<String> mData = new ArrayList<String>(mList);
ArrayList<String> mSuggestions = new ArrayList<String>(mList);