SearchView不会在第二个点上调用onQueryTextChange [英] SearchView not calls onQueryTextChange on second dot

查看:259
本文介绍了SearchView不会在第二个点上调用onQueryTextChange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的活动有SearchView,应该已过滤查询.我正在通过onQueryTextListener对其进行过滤.想法是禁止键入不允许的字符,例如点,逗号,斜杠等-仅允许[A-Z] 这是代码(我正在使用Kotlin,但是对于Java来说是可读的):

My Activity has SearchView, which should have filtered query. I am filtering it via onQueryTextListener. Idea is that disable typing not allowed chars, like dot, comma, slash and etc - only [A-Z] is allowed Here is code (I am using Kotlin, but it is readable for Java):

var shouldQueryChangeBeInvoked = true

override fun onCreate(savedInstanceState: Bundle?) {
    ...
    searchField.setOnQueryTextListener(this)
}

override fun setSearchQuery(query: String) {
    shouldQueryChangeBeInvoked = false
    searchField.setQuery(query, false)
    shouldQueryChangeBeInvoked = true
}

override fun onQueryTextChange(newText: String?): Boolean {
    if (!shouldQueryChangeBeInvoked) {
        return false
    }
    val validQuery = validateQuery(newText)
    validQuery?.let { setSearchQuery(it) }
    return false
}

例如,当我键入"ABC"时.它将转换为"ABC".因此,它工作正常. 但是,当我第二次键入dot(.")时,onQueryTextChange根本不会调用-我在方法的第一行设置了断点. 它已经在两部不同的手机上进行了测试,因此不是键盘设置或类似的设置. 为什么监听器不调用?

When I type, for example, "ABC." it converts to "ABC". So, it works fine. But when I type dot(".") second time onQueryTextChange doesn't invokes at all - I have set breakpoint on first line of the method. It was tested on two different phones, so it is not keyboard settings or smth like that. Why listener doesn't invoke?

编辑

我使用Regex进行的查询验证如下:

Validation of query I making with Regex like that:

fun validateQuery(query: String?): String? {
    val regex = Regex("^([A-Z]+)")
    // Return first match or null
    return query?.let { regex.find(it.toUpperCase()) }?.value
}

不在乎正则表达式的创建-我通过DI提供它,因此,每个活动仅创建一次. 也许有问题吗?

Don't care about Regex creation - I provide it via DI, so, it creates only once per activity. Maybe it can be problem?

推荐答案

非常感谢@pskink!

Thanks a lot to @pskink!

我已经实现了带有过滤器输入查询的自定义SearchView,并且能够在setQuery上禁用触发onQueryTextChange的功能. 是科特林,让我们继续讲那美丽的语言吧:) 我希望这对某人有用.

I have implemented custom SearchView with filter input query and ability to disable triggering onQueryTextChange on setQuery. It is Kotlin, let's move on to that beautiful language :) I hope it will be useful for someone.

这里是关于Gist的代码

这篇关于SearchView不会在第二个点上调用onQueryTextChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆