如何使用 Volley 库在 android recyclerView 中添加搜索功能

how to add Search functionality in android recyclerView using Volley library

我正在制作 android 应用程序,我在其中搜索 RecyclerView 项目。请求将成功发送到服务器。基本上我正在使用关键字进行搜索。问题是我如何将搜索关键字发送到服务器并根据该关键字加载数据。 这是我的搜索活动:

在 onTextChanged() 中调用 getData() 方法并从搜索栏中获取字符串作为

searchItem = s.toString();

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int 
        count) {
        Log.d("onTextChanged", getClass().getSimpleName() + " text 
        changed " + searchBar.getText());
        searchItem = s.toString();
        Log.d("Text",searchItem);
        getData();
    }

将 TextWatcher 与 TimerTask 结合使用以避免不必要的 api 触发器

在您的 onTextChanged()

中调用 startTask()
    private Timer timer;
    private TimerTask timerTask;

    private void startTask() {
            cancelTimers();
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    initSearch();
                }
            };
            timer.schedule(timerTask, 500);
        }

private void initSearch() {
    if (searchView != null && searchView.getQuery() != null) {
        String query = editText.getText().toString();
        setupAdapter(query);
    } else {
        setupAdapter(null);
    }
}



 private void setupAdapter(String query) {
        if (query != null) {
            // start Api call
        } else {
            //clearResults();
        }
    }



 private void cancelTimers() {
        if (timer != null) {
            timer.cancel();
            timer.purge();
        }
        if (timerTask != null) {
            timerTask.cancel();
        }
    }