我正在使用带有普通TextView的283项的Recycler View来过滤列表。
我想一直只显示10条记录。
我不能使用getCount(或GetItemCount),因为当我过滤列表时它给了我IndexOutOfBoundsExceptions,有没有其他方法可以做到这一点?
public class RealmAutoCompleteAdapter extends RecyclerView.Adapter<RealmAutoCompleteAdapter.ProductViewHolder> {
Realm realm;
RealmChangeListener<RealmResults<FieldsItem>> realmChangeListener;
RealmResults<FieldsItem> items;
String searchTerm;
public RealmAutoCompleteAdapter(Realm realm, RealmResults<FieldsItem> items) {
this.realm = realm;
this.realmChangeListener = new RealmChangeListener<RealmResults<FieldsItem>>() {
@Override
public void onChange(RealmResults<FieldsItem> results) {
notifyDataSetChanged();
}
};
this.items = items;
items.addChangeListener(realmChangeListener);
}
@Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ProductViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.autocomplete_row, parent, false));
}
@Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
FieldsItem item = items.get(position);
holder.title.setText(item.getTitle());
}
public void updateInput(String input) {
this.searchTerm = input;
if(items != null && items.isValid()) {
items.removeAllChangeListeners();
}
RealmQuery<FieldsItem> query = realm.where(FieldsItem.class);
if(searchTerm != null && !"".equals(searchTerm)) {
query = query.contains("title", searchTerm, Case.INSENSITIVE);
}
items = query.findAll();
items.addChangeListener(realmChangeListener);
notifyDataSetChanged();
}
@Override
public int getItemCount() {
if(items == null || !items.isValid()) {
return 0;
}
return items.size();
}
static class ProductViewHolder extends RecyclerView.ViewHolder {
TextViewWithFont title;
ProductViewHolder(View itemView) {
super(itemView);
title = (TextViewWithFont)itemView.findViewById(R.id.title);
}
}
}
答案 0 :(得分:6)
你可以这样做:
return Math.min(items.size(), 10);