首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何提高文本转换Android中的搜索性能

如何提高文本转换Android中的搜索性能
EN

Stack Overflow用户
提问于 2018-03-12 08:22:07
回答 1查看 701关注 0票数 0

我有一个textWatcher来检测搜索栏中的文本变化。一旦发生文本更改,它将立即执行搜索操作。

例如,当我在搜索栏中键入"a“时,它将在For循环中运行itemData.name.toLowerCase().contains("a");,以搜索名称包括"a”的项,并将其显示在循环视图中。

然后我继续输入"b",它将再次在for循环中运行itemData.name.toLowerCase().contains("ab");,以搜索名称包括"ab“的项。

这就是我的想法

代码语言:javascript
代码运行次数:0
运行
复制
//this will run when text change occur
for(){//for all item of itemlist
    if(){//if item name contains the text 
        //store this item in itemlist
    }
}
//update new itemlist to recycle view here

然而,表演却非常缓慢。当我输入搜索栏时,它会有一些滞后。有人能解决这个问题吗?

EN

回答 1

Stack Overflow用户

发布于 2018-03-12 08:40:36

在自动完成过程中,您希望每次击键都会对结果进行过滤。相反,您希望在完成键入之后触发搜索。如果用户没有完成键入他的关键字,我们将执行一个搜索请求与每一个键键入。

为了避免如此多的请求并优化搜索体验,您可以为搜索字段TextWatcher使用EditText

代码语言:javascript
代码运行次数:0
运行
复制
private EditText searchText;  
private TextView resultText;  
private Timer timer;

    private TextWatcher searchTextWatcher = new TextWatcher() {  
        @Override
        public void afterTextChanged(Editable arg0) {
            // user typed: start the timer
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // do your actual work here
                }
            }, 600); // 600ms delay before the timer executes the „run“ method from TimerTask
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // nothing to do here
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // user is typing: reset already started timer (if existing)
            if (timer != null) {
                timer.cancel();
            }
        }
    };

这段代码片段只是向您展示了解决问题的示例用例,即如何猜测用户何时完成输入,并希望在没有提交按钮的情况下启动搜索。我们使用600毫秒的延迟开始搜索。如果用户在搜索字段中键入另一个字母,我们会重置计时器,然后再等待600 ms。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49230819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档