【问题标题】:Search string inside WebView in Kotlin/Android在 Kotlin/Android 中的 WebView 中搜索字符串
【发布时间】:2018-08-29 18:08:12
【问题描述】:

我是 Android 和 Kotlin 的新手。我正在开发一个从站点获取 HTML 文件并将其显示在 WebView 中的应用程序。我需要在WebNavigators 中构建一个作为 Ctrl-F (查找命令)的功能,以查找搜索的字符串并滚动屏幕直到找到匹配字符串。以及下一个和上一个匹配的按钮。

我正在尝试以下代码,但它不起作用:

myWebView.findAllAsync("Test in HTML file") 
myWebView.findNext(true) 

谁能帮助我或给我一个方向?

【问题讨论】:

    标签: java android kotlin


    【解决方案1】:

    以下 Kotlin 函数是相当标准的搜索功能:

    operator fun CharSequence.contains(
        char: Char, 
        ignoreCase: Boolean = false
    ): Boolean (source)
    

    在WebView中.contains()方法在if-statement里面更有用:

    import android.webkit.WebView
    
    val str: String = // blah-blah-blah ;
    
    if (str.contains("Test in HTML file", false))
        return true
    

    希望这会有所帮助!

    【讨论】:

    • 谢谢,非常有用,但不是我真正需要的。
    【解决方案2】:

    终于,经过一番搜索,我找到了答案。在这里发帖,因为可能对任何人都有用。 基于this articlethis ask,我确实构建了我的代码:

       override fun onCreate(savedInstanceState: Bundle?) {
         /// *... blah blah my code no related to this issue*
        wv_contentArticle.loadUrl("file:///android_asset/articles/w.html") // loading file - just a test
        sv_contentPage.isSubmitButtonEnabled
        // bellow listen the searchview 
    
        sv_contentPage.setOnQueryTextListener(object :    SearchView.OnQueryTextListener {
            override fun onQueryTextChange(query: String): Boolean {
                return true
            }
            override fun onQueryTextSubmit(query: String): Boolean {
    
                if (!query.isEmpty()) {
                        sv_contentPage.clearFocus()  // to hide keyboard 
                        wv_contentArticle.findAllAsync(query) // look for string
                        try {
                            val m = WebView::class.java.getMethod("setFindIsUp", 
    java.lang.Boolean.TYPE) // THIS WAS MISSING, WITHOUT IT THIS WILL NOT WORK
                            m.invoke(wv_contentArticle, true) // THIS WAS MISSING, WITHOUT IT THIS WILL NOT WORK
    
                        } catch (ignored: Throwable) {
                        }
                }
            return true
            }
        })
        bt_findNext.setOnClickListener {  wv_contentArticle.findNext(true)  } // find next one
        bt_findPrevious.setOnClickListener {  wv_contentArticle.findNext(false) } // find previous one
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-29
      • 1970-01-01
      • 2016-12-01
      • 2016-11-30
      • 2016-01-08
      • 2020-10-30
      相关资源
      最近更新 更多