【问题标题】:how to add Search functionality in android recyclerView using Volley library如何使用 Volley 库在 android recyclerView 中添加搜索功能
【发布时间】:2019-01-11 05:07:49
【问题描述】:

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

【问题讨论】:

  • 您是否尝试过改用 Retrofit?它在 Google 的官方“应用架构指南”中被推荐。 developer.android.com/jetpack/docs/guide#fetching_data
  • 不,我正在使用 volley 编写整个代码。这就是我使用凌空抽射的原因
  • 当您进行搜索时,您已经使用您要使用的列表填充了您的回收站视图?或者您需要使用搜索视图向服务器发出请求以检索列表?
  • 是的。我正在使用特定关键字向服务器发送请求。该关键字将从服务器检索数据

标签: android android-studio android-recyclerview android-volley searchview


【解决方案1】:

在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();
    }

【讨论】:

  • 是的。这是有效的,但也显示不相关的项目
  • 更新 UI 需要时间,因为如果你想搜索文本,那么首先 api 调用 t 然后 te 然后 tex 和最后一个文本所以显示加载器然后你会在最后一次得到相关列表
  • 如果你通过这个答案解决了这个问题,那么就给这个问题打分@ansarabbas
【解决方案2】:

将 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();
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-06
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    相关资源
    最近更新 更多