Android开发搜索功能,需要监听输入框,用户实时输入便启动请求后台搜索结果,但是用户快速输入每一个单词,就触发一次服务器请求,有点浪费资源,且体验不好,做法是等待用户比如500ms后,再进行搜索请求,以下是Android代码:
新建一个类:Debouncer.java
class Debounce { private Handler mHandler = new Handler(); private long mInterval; public Debounce(long interval) { mInterval = interval; } public void attempt(Runnable runnable) { mHandler.removeCallbacksAndMessages(null); mHandler.postDelayed(runnable, mInterval); } }
如何调用
Debounce debounce = new Debounce(300); public void searchChanged(final String keywords) { debounce.attempt(new Runnable() { @Override public void run() { new SearchTask(progressBar).execute(keywords); } }); }
Java语言通用版本,请看https://blog.terrynow.com/2020/12/21/java-debounce/
Swift版本,请看https://blog.terrynow.com/2020/12/22/ios-swift-debounce/
Javascript版本,请看https://blog.terrynow.com/2020/12/23/javascript-debounce/
文章评论