13

I am writing a search function to access a library website.And when the query string is submitted,program launches a new thread to parse infos on the web. it runs normally on AVD but my HTC DesireHD displayed the search results repeatedly,(if the real results are 1. 2. 3. it would appears to be 1. 2. 3. 1. 2. 3.). I set breakpoints at the onQueryTextSubmit method ,found that codes in method onQueryTextSubmit() were executed twice. and here is my code:

sv.setOnQueryTextListener(new OnQueryTextListener(){

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            list.clear();
            String str = null;
            try {//encoding Chinese character
                str = new String(query
                        .trim().getBytes(), "ISO-8859-1");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            SearchPost sp = new SearchPost(SEARCH_URL + str);
            new Thread(sp).start(); 
            return false;
        }
    });

protected class SearchPost implements Runnable{
    public String url = "";
    SearchPost(String urls){
        url = urls;
    }
    public SearchPost() {
    }
    @Override
    public void run() {
        Message message = handler.obtainMessage();
        message.what = DOWNLOAD_COMPLETE;
        try{
            doc = Jsoup.connect(url).get();
                handler.sendMessage(message);
        }catch(IOException e){
            e.printStackTrace();
            message.what = DOWNLOAD_FAIL;
            handler.sendMessage(message);
        }
    }
}
4

5 回答 5

31

清除对SearchView的关注对我有帮助。

sv.clearFocus();

注意:这也会隐藏键盘。

于 2013-10-29T10:09:14.383 回答
4

找出为什么单击按钮一次会导致 onQueryTextSubmit 触发两次,这本身就是一个您可能无法解决的问题,因为它由可能有问题的操作系统控制。真正的问题是正确处理快速连续单击按钮两次或更多次的情况,这可能会产生相同的效果。我建议将 list.clear() 移动到您填充列表的同一位置。

于 2013-07-26T07:25:39.187 回答
2

由于问题是用户按下键盘上的搜索键会产生两个键事件 ACTION_DOWN 和 ACTION_UP,并且某些设备会对这两个消息做出反应。

我以一种简单的方式解决了,因为我不喜欢 setIconified(),因为,然后搜索到的文本被删除,我只让每秒搜索一次,所以这样做了:

public boolean onQueryTextSubmit(String s) {

    long actualSearchTime = (Calendar.getInstance()).getTimeInMillis();
    // Only one search every second to avoid key-down & key-up          
    if (actualSearchTime > lastSearchTime + 1000)
    {
        lastSearchTime=actualSearchTime;
    }
}
于 2014-10-17T17:04:53.623 回答
1

我遇到了这个问题,因为我使用了 _searchView.setInputType(InputType.TYPE_NULL);,所以通过删除这一行,onQueryTextSubmit 函数调用了一次

于 2014-12-07T16:18:23.693 回答
1

我一直在寻找这件事的原因和解决方案,并找到了一些东西。发生这种情况的原因: https ://code.google.com/p/android/issues/detail?id=24599

用户在键盘上按下搜索键的动作会产生两个键事件 ACTION_DOWN 和 ACTION_UP,并且某些设备会对这两个消息做出反应(应该只对 ACTION_UP 做出反应),原来是 SDK 或设备本身的错误我们开发人员无法控制。

为了解决这个问题,我添加了“sv.setIconified()”来清空查询文本,以使 ACTION_UP 无效。

于 2013-07-27T09:25:09.270 回答