当前位置: 首页 > 知识库问答 >
问题:

回收器查看过滤器不工作

柴宏浚
2023-03-14

我使用此解决方案来过滤我的RecyclView。使用该解决方案,我能够在键入时获得结果。但是当我清除搜索小部件时,我没有得到完整的列表,而是得到了空的RecyclView

这就是我的结果。https://imgur.com/nwyetEd

这是我的适配器

public class ContactsAdapter extends RecyclerView.Adapter<ContactViewHolder> {

    private LayoutInflater inflater;
    private ContactViewHolder viewHolder;
    private ArrayList<Contact> contactsList = new ArrayList<>();
    private VolleySingleton volleySingleton;
    private ImageLoader imageLoader;
    boolean fromMyContacts;
    Context context;

    public ContactsAdapter(Context context, boolean fromMyContacts){
        inflater = LayoutInflater.from(context);
        this.context = context;
        volleySingleton = VolleySingleton.getsInstance();
        imageLoader = volleySingleton.getImageLoader();
        this.fromMyContacts = fromMyContacts;
    }

    public void setContactsList(ArrayList<Contact> contactsList){
        this.contactsList = contactsList;
        notifyItemRangeChanged(0, contactsList.size());
    }

    @Override
    public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.contact_list, parent, false);
        viewHolder = new ContactViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ContactViewHolder holder, int position) {
        Contact current = contactsList.get(position);
        viewHolder.name.setText(current.name);
        viewHolder.phone.setText(current.phone);
        viewHolder.city.setText(current.location + ", " + current.city);

        if(fromMyContacts) {
            if (current.verified) {
                viewHolder.verified.setImageResource(R.drawable.ic_check_circle);
            } else {
                viewHolder.verified.setImageResource(R.drawable.ic_cancel);
            }
        }

        String image_url = current.image_url;
        if(!image_url.equals("null")){
            Picasso.with(context).load(image_url).into(viewHolder.contactIcon);
        }else{
            viewHolder.contactIcon.setImageResource(R.drawable.contact_icon);
        }
    }

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

    public Contact removeItem(int position){
        final Contact contacts = contactsList.remove(position);
        notifyItemRemoved(position);
        return contacts;
    }

    public void addItem(int position, Contact contactList){
        contactsList.add(position, contactList);
        notifyItemInserted(position);
    }

    public void moveItem(int fromPosition, int toPosition){
        final Contact contacts = contactsList.remove(fromPosition);
        contactsList.add(toPosition, contacts);
        notifyItemMoved(fromPosition, toPosition);
    }

    public void animateTo(List<Contact> contacts){
        applyAndAnimateRemovals(contacts);
        applyAndAnimateAdditions(contacts);
        applyAndAnimateMovedItems(contacts);
    }

    private void applyAndAnimateRemovals(List<Contact> newModels) {
        for (int i = contactsList.size() - 1; i >= 0; i--) {
            final Contact model = contactsList.get(i);
            if (!newModels.contains(model)) {
                removeItem(i);
            }
        }
    }

    private void applyAndAnimateAdditions(List<Contact> newModels) {
        for (int i = 0, count = newModels.size(); i < count; i++) {
            final Contact model = newModels.get(i);
            if (!contactsList.contains(model)) {
                addItem(i, model);
            }
        }
    }

    private void applyAndAnimateMovedItems(List<Contact> newModels) {
        for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
            final Contact model = newModels.get(toPosition);
            final int fromPosition = contactsList.indexOf(model);
            if (fromPosition >= 0 && fromPosition != toPosition) {
                moveItem(fromPosition, toPosition);
            }
        }
    }
}

这是我的Model

public class Contact {

    String name;
    String phone;
    String city;
    String location;
    Boolean verified;
    String image_url;

    public Contact(String name, String phone, String city, String location, Boolean verified, String image_url){
        this.name = name;
        this.phone = phone;
        this.city = city;
        this.location = location;
        this.verified = verified;
        this.image_url = image_url;
    }

}

这是我使用过滤器的< code >活动

public class MyContactsActivity extends AppCompatActivity implements View.OnClickListener, SearchView.OnQueryTextListener {

    private RecyclerView recyclerView;
    private ContactsAdapter adapter;
    private NetworkChecker networkChecker;
    private SessionManager sessionManager;
    private AppConfig appConfig;
    private RelativeLayout loading, retry;
    private Button tryAgain;
    AlertHelper alertHelper;
    final ArrayList<Contact> contactArrayList = new ArrayList<>();
    String url;

    DebugHelper debugHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_contacts);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        debugHelper = new DebugHelper();

        loading = (RelativeLayout) findViewById(R.id.loadingPanel);
        retry = (RelativeLayout) findViewById(R.id.retry);
        tryAgain = (Button) findViewById(R.id.tryAgainButton);

        tryAgain.setOnClickListener(this);

        alertHelper = new AlertHelper(this);
        networkChecker = new NetworkChecker(this);
        sessionManager = new SessionManager(this);
        appConfig = new AppConfig();

        String phone = sessionManager.getLoggedInUserPhone();
        url = appConfig.getApiUrlForSpecificContacts(phone);



        recyclerView = (RecyclerView) findViewById(R.id.contactsView);
        adapter = new ContactsAdapter(getApplicationContext(), true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        sendJsonRequest(url);
        recyclerView.setAdapter(adapter);

        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        TextView phone = (TextView) view.findViewById(R.id.contact_phone);
                        TextView name = (TextView) view.findViewById(R.id.contact_name);
                        Intent i = new Intent(getApplicationContext(), ContactProfileActivity.class);
                        i.putExtra("selected_user_phone", phone.getText());
                        i.putExtra("selected_user_name", name.getText());
                        startActivity(i);
                    }
                })
        );

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), AddContactActivity.class));
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    private void sendJsonRequest(String url) {
        if (networkChecker.networkAvailable()) {
            loading.setVisibility(View.VISIBLE);
            RequestQueue requestQueue = VolleySingleton.getsInstance().getmRequestQueue();

            StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    loading.setVisibility(View.GONE);
                    retry.setVisibility(View.GONE);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray jsonArray = jsonObject.getJSONArray("contact_info");

                        if(jsonArray != null){
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject currentContact = jsonArray.getJSONObject(i);

                                String name = currentContact.getString("name");
                                String phone = currentContact.getString("phone");
                                String city = currentContact.getString("city");
                                String address = currentContact.getString("address");
                                Boolean verified = currentContact.getBoolean("verified");
                                String image_url = currentContact.getString("image_url");

                                Contact contact = new Contact(name, phone, city, address, verified, image_url);

                                contactArrayList.add(contact);

                            }
                            adapter.setContactsList(contactArrayList);
                        }
                        else{
                            alertHelper.displayDialog("No Contacts Found.");
                        }
                    }catch (Exception e){
                        retry.setVisibility(View.VISIBLE);
                        tryAgain.setClickable(true);
                        alertHelper.displayDialog(getString(R.string.action_failed_try_again));
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    loading.setVisibility(View.GONE);
                    retry.setVisibility(View.VISIBLE);
                    tryAgain.setClickable(true);
                    if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                        alertHelper.displayDialog(getString(R.string.connection_failed));
                    } else {
                        alertHelper.displayDialog(getString(R.string.action_failed_try_again));
                    }
                }
            });

            requestQueue.add(stringRequest);

        } else {
            retry.setVisibility(View.VISIBLE);
            tryAgain.setClickable(true);
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.contact_list_menu, menu);
        debugHelper.L("Search Click Vayo");
        final MenuItem item = menu.findItem(R.id.action_search);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
        searchView.setOnQueryTextListener(this);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch (id) {
            case android.R.id.home:
                onBackPressed();
                return true;

        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tryAgainButton:
                sendJsonRequest(url);
                break;
        }
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String query) {
        final List<Contact> filteredModelList = filter(contactArrayList, query);
        adapter.animateTo(filteredModelList);
        recyclerView.scrollToPosition(0);
        return true;
    }

    private List<Contact> filter(List<Contact> models, String query) {
        query = query.toLowerCase();
        if(query.equals("")) { return contactArrayList; }
        final List<Contact> filteredModelList = new ArrayList<>();
        for (Contact model : models) {
            final String text = model.name.toLowerCase();
            if (text.contains(query)) {
                filteredModelList.add(model);
            }
        }
        return filteredModelList;
    }

有人能帮助我吗?

共有3个答案

孟晋
2023-03-14

您需要将您的filter()方法从您的活动移动到您的适配器。在您的适配器中添加一个附加变量来保存未过滤数据集的副本。在您的情况下,您需要contactsListCopOfContactsList变量。

按如下方式更改适配器的构造函数:

public class ContactsAdapter extends RecyclerView.Adapter<ContactViewHolder> {

    ....
    private ArrayList<Contact> contactsList = new ArrayList<>();
    private ArrayList<Contact> copyOfContactsList = new ArrayList<>();
    ....

    public ContactsAdapter(Context context, ArrayList<Contact> dataSet, boolean fromMyContacts){
        ...
        this.contactsList = dataSet;
        copyOfContactsList.addAll(dataSet);
        ...
    }

这是要添加到< code >适配器中的筛选方法:

public void filter(String text) {
    if(text.isEmpty()){
        contactsList.clear();
        contactsList.addAll(copyOfContactsList);
    } else{
        ArrayList<Contact> result = new ArrayList<>();
        text = text.toLowerCase();
        for(Contact item: copyOfContactsList){
            if(item.getName().toLowerCase().contains(text)){
                result.add(item);
            }
        }
        contactsList.clear();
        contactsList.addAll(result);
    }
    notifyDataSetChanged();
}
沈树
2023-03-14

他以这种方式定义

public void setModels(List<ExampleModel> models) {
    mModels = new ArrayList<>(models);
}

像他所做的那样初始化。

你的祝福将是:

this.contactsList = new ArrayList<>(contactsList);
双志强
2023-03-14

假设contactsList是具有完整触点的var

    private List<Contact> filter(List<Contact> models, String query) {
    query = query.toLowerCase();
    if(query.equals("")) { return contactsList; }

    final List<Contact> filteredModelList = new ArrayList<>();
    for (Contact model : models) {
        final String text = model.name.toLowerCase();
        if (text.contains(query)) {
            filteredModelList.add(model);
        }
    }
    return filteredModelList;
}
 类似资料:
  • 我正试图在我的RecyclerView中实现搜索过滤器,就像在这篇文章中一样 我已经对它进行了调试,它确实按照预期过滤了项目,但列表在应用程序中似乎没有改变。一、 E:我过滤一个名字,有7个结果,在屏幕上是原始列表。 我的 onCreateMenu活动选项是: 我的适配器如下所示: 我忘了什么? 提前致谢!

  • 我使用SearchView过滤我的应用程序的RecyclerView,就像这篇文章中描述的一样: 如何使用SearchView筛选RecyclerView 一开始一切看起来都很好,我可以根据需要过滤RecyclerView,但是经过一些尝试,出现了两个问题: 如果我在SearchView中输入文本太快,应用程序会崩溃,并出现以下日志: E/AndroidRuntime: FATAL EXCEPTI

  • 我有这个回收器视图,我从Retrofit API获取数据,问题是当我尝试在回收器中制作过滤器时,我在互联网上搜索,所有示例都是字符串列表,但我有对象列表,我如何解决这种情况并在工具栏中创建过滤器?我会发布我的代码,希望有人能帮忙,谢谢 活动 这是适配器 这是菜单

  • 实际上,我尝试在一个类中设置imageView ColorFilter,该类定义了适配器avec recycle view。为此,我在我的适配器中定义了一个ImageView ArrayList,它从viewholder中存储了我的ImageView,我还在我的适配器中用一个带有position参数的自定义方法来获取它们。但它并不真的工作,当我点击我的项目,颜色过滤器是随机适用于我的recycle

  • 当我尝试使用时,我得到一个异常。下面是堆栈跟踪: 编辑二:

  • 在过去的三天里,我一直在与错误“跨源请求被阻止:相同的源策略不允许读取http://localhost:8080/demomongo/templateapp/login上的远程资源。”(原因:缺少CORS头'Access-Control-Allow-Origin')。