1 回答
TA贡献1780条经验 获得超4个赞
对于您的适配器,您创建了一个名为filter的公共方法,它不是真正的Filter类。我建议使用 2 种不同的方法来使发布的代码正常工作。
方法一:在Activity中,将:adapter.getFilter().filter(newText);改为adapter.filter(newText);。
方法 2:由于您的数据是一个String列表并且 ArrayAdapter 已经是Filterable,所以保留adapter.getFilter().filter(newText);并使适配器像这样简单:
public class ListViewAdapter extends ArrayAdapter {
private MainActivity activity;
public ListViewAdapter(MainActivity context, int resource, List<String> objects) {
super(context, resource, objects);
this.activity = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.item_listview, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
String item = (String)getItem(position);
holder.friendName.setText(item);
//get first letter of each String item
String firstLetter = item.substring(0, 1);
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getColor(item);
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
holder.imageView.setImageDrawable(drawable);
return convertView;
}
private class ViewHolder {
private ImageView imageView;
private TextView friendName;
public ViewHolder(View v) {
imageView = (ImageView) v.findViewById(R.id.image_view);
friendName = (TextView) v.findViewById(R.id.text);
}
}
}
我在 ListView 上的博客还包含带有过滤器的示例:http: //programandroidlistview.blogspot.com/希望对您有所帮助!
添加回答
举报