ArrayAdapter自定义过滤器不起作用

时间:2018-04-03 11:10:47

标签: android android-arrayadapter

我的自定义过滤器出了问题。我做到了,它运作良好。当我调试代码时,它很好地过滤了数组,但我在void publishResults()中遇到了问题。我不知道什么是问题,有人帮忙吗?

public class KatalogAdapter extends ArrayAdapter<Katalog> implements Filterable {

List<Katalog> object;
int num = 0;


public KatalogAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<Katalog> objects) {


    super(context, resource, objects);
    object = objects;
}

public void setObject(List<Katalog> kat){
    this.object = kat;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View v = convertView;

    if(v==null) {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.katalozi_item, null);
    }


        Katalog katalog = object.get(position);
        ImageView katalogImage = (ImageView) v.findViewById(R.id.katalogImage);
        TextView katalogProizvodjac = (TextView) v.findViewById(R.id.katalogProizvodjac);
        TextView katalogVaziDo = (TextView) v.findViewById(R.id.katalogVaziDo);
        TextView idKataloga = (TextView) v.findViewById(R.id.idKataloga);

        String src = katalog.getImageSRC();

        Picasso.with(getContext()).load(src).into(katalogImage);
    /*Glide.with(getContext()).load(src).thumbnail(Glide.with(getContext()).load(R.drawable.loading_icon))
            .fitCenter()
            .crossFade().into(katalogImage); */

        // katalogImage.setImageBitmap(bitmap);
        katalogProizvodjac.setText(katalog.getKatalogProizvodjac());

        String doe = katalog.getKatalogVaziDo();
        char lastChar = doe.charAt(doe.length() - 1);
        if(lastChar=='1'){
            katalogVaziDo.setText("Važi još "+ doe +" dan");
        }
        if(doe.equals("0")){
            katalogVaziDo.setText("Važi još danas");
        }
        if(lastChar!='1' && !doe.equals("0")){
            katalogVaziDo.setText("Važi još "+katalog.getKatalogVaziDo() + " dana");
        }
        //  katalogVaziDo.setText("Važi do: "+katalog.getKatalogVaziDo());
        idKataloga.setText(String.valueOf(katalog.getIdKataloga()));



        return  v;

    }

@Override
public Filter getFilter() {

    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults filterResults = new FilterResults();
            ArrayList<Katalog> tempList=new ArrayList<Katalog>();
            //constraint is the result from text you want to filter against.
            //objects is your data set you will filter from
            if(constraint != null && object!=null) {
                int length=object.size();
                int i=0;
                while(i<length){
                    Katalog item=object.get(i);
                    if(item.getKatalogProizvodjac().toLowerCase(Locale.getDefault()).contains(constraint.toString().toLowerCase())){
                        tempList.add(item);
                    }



                    i++;
                }
                //following two lines is very important
                //as publish result can only take FilterResults objects
                filterResults.values = tempList;
                filterResults.count = tempList.size();
            }
            return filterResults;
        }
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {

          //  object = (ArrayList<Katalog>) results.values;
            setObject((List<Katalog>) results.values);
            num = results.count;


                notifyDataSetChanged();

        }
    };
}

}

我正在寻找答案,我发现在该函数中我需要将数据放入数组中。我做到了,但仍然没有用。

2 个答案:

答案 0 :(得分:1)

我提供带有过滤器的recyler视图适配器以获取联系人详细信息,您可以根据需要更改所需的代码。

public class InviteContactAdapter extends RecyclerView.Adapter<InviteContactAdapter.ItemViewHolder> implements Filterable {
private List<UserContact> mContactList = new ArrayList<>();
private List<UserContact> mContectFilter = new ArrayList<>();
private Context mContext;
private CustomFilter mFilter;
public List<String> mEmailList = new ArrayList<>();

public InviteContactAdapter(Context context, List<UserContact> mContactList) {
    mContext = context;
    this.mContactList = mContactList;
    this.mContectFilter = mContactList;
    mFilter = new CustomFilter();
}

public onItemClickListener onItemClickListener;

public void setOnItemClickListener(InviteContactAdapter.onItemClickListener onItemClickListener) {
    this.onItemClickListener = onItemClickListener;
}

@Override
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.invite_contact_row_layout, viewGroup, false);
    return new ItemViewHolder(view);
}

public interface onItemClickListener {
    void onClick(UserContact contact);
}

@Override
public Filter getFilter() {
    return mFilter;
}

@Override
public void onBindViewHolder(final ItemViewHolder itemViewHolder, int i) {
    final UserContact contact = mContectFilter.get(i);
    itemViewHolder.mTvUserNane.setText(contact.getUserName().trim());
    itemViewHolder.mTvUserEmail.setText(contact.getUserEmail().trim());
    if (contact.isSelect())
        itemViewHolder.mIvSelect.setImageResource(R.drawable.check_contect);
    else
        itemViewHolder.mIvSelect.setImageResource(R.drawable.un_check_contact);


    itemViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (contact.isSelect()) {
                contact.setSelect(false);
                itemViewHolder.mIvSelect.setImageResource(R.drawable.un_check_contact);
            } else {
                contact.setSelect(true);
                itemViewHolder.mIvSelect.setImageResource(R.drawable.check_contect);
            }
        }
    });

}

@Override
public int getItemCount() {
    return mContectFilter.size();
}

public class ItemViewHolder extends RecyclerView.ViewHolder {
    private TextView mTvUserNane, mTvUserEmail;
    private ImageView mIvSelect;

    public ItemViewHolder(View itemView) {
        super(itemView);
        mTvUserEmail = itemView.findViewById(R.id.icrlTvUserEmail);
        mTvUserNane = itemView.findViewById(R.id.icrlTvUserName);
        mIvSelect = itemView.findViewById(R.id.icrlIvSelect);
    }
}

public List<String> getEmail() {
    mEmailList.clear();
    for (UserContact contact : mContectFilter) {
        if (contact.isSelect()) {
            mEmailList.add(contact.getUserEmail());
        }
    }
    return mEmailList;
}

/**
 * this class for filter data.
 */
class CustomFilter extends Filter {

    @Override
    protected FilterResults performFiltering(CharSequence charSequence) {
        FilterResults results = new FilterResults();
        if (charSequence != null && charSequence.length() > 0) {
            ArrayList<UserContact> filters = new ArrayList<>();
            charSequence = charSequence.toString().toUpperCase();
            for (int i = 0; i < mContactList.size(); i++) {
                if (mContactList.get(i).getUserName().toUpperCase().contains(charSequence) || mContactList.get(i).getUserEmail().toUpperCase().contains(charSequence)) {
                    UserContact contact = new UserContact();
                    contact.setUserName(mContactList.get(i).getUserName());
                    contact.setUserEmail(mContactList.get(i).getUserEmail());
                    filters.add(contact);

                }
            }
            results.count = filters.size();
            results.values = filters;

        } else {
            results.count = mContactList.size();
            results.values = mContactList;
        }
        return results;
    }

    @Override
    protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
        mContectFilter = (ArrayList<UserContact>) filterResults.values;
        notifyDataSetChanged();
    }
}

}

并调用以下过滤器记录的edittext框中的活动。 过滤数据 注意:确保您的适配器对象不为空

/** 
 * this method filter data.
 */
private void sortData(View root) {
    mEtSearchData = (EditText) root.findViewById(R.id.icffEtSearch);
    mEtSearchData.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (inviteContactAdapter != null) {
                inviteContactAdapter.getFilter().filter(s);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

}

答案 1 :(得分:0)

我的问题是在某些行中我讨厌gridView.setAdapter(null)。 但是,我还有一个问题,在gridView我有5个元素,过滤后,我有一个项目填充了真实数据和4个空项目。所以,我改变了getView函数.. 如果有人需要它,这里是:

public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View v = convertView;

    if(v==null) {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.katalozi_item, null);
    }


if(objectfilt.size()>position){


        Katalog katalog = objectfilt.get(position);
        ImageView katalogImage = (ImageView) v.findViewById(R.id.katalogImage);
        TextView katalogProizvodjac = (TextView) v.findViewById(R.id.katalogProizvodjac);
        TextView katalogVaziDo = (TextView) v.findViewById(R.id.katalogVaziDo);
        TextView idKataloga = (TextView) v.findViewById(R.id.idKataloga);

        String src = katalog.getImageSRC();

        Picasso.with(getContext()).load(src).into(katalogImage);
    /*Glide.with(getContext()).load(src).thumbnail(Glide.with(getContext()).load(R.drawable.loading_icon))
            .fitCenter()
            .crossFade().into(katalogImage); */

        // katalogImage.setImageBitmap(bitmap);
        katalogProizvodjac.setText(katalog.getKatalogProizvodjac());

        String doe = katalog.getKatalogVaziDo();
        char lastChar = doe.charAt(doe.length() - 1);
        if(lastChar=='1'){
            katalogVaziDo.setText("Važi još "+ doe +" dan");
        }
        if(doe.equals("0")){
            katalogVaziDo.setText("Važi još danas");
        }
        if(lastChar!='1' && !doe.equals("0")){
            katalogVaziDo.setText("Važi još "+katalog.getKatalogVaziDo() + " dana");
        }
        //  katalogVaziDo.setText("Važi do: "+katalog.getKatalogVaziDo());
        idKataloga.setText(String.valueOf(katalog.getIdKataloga()));
return  v;

}
else {
v.setVisibility(View.GONE);
return v;
}

因此,添加了ListArray objectfilt中的元素,当int position变得大于ListView元素的数量时,只需隐藏该视图。