首页 > 解决方案 > 两个相似的代码结构,但一个不起作用

问题描述

以下是本质上应该做同样事情的两个代码块。但是第二个不执行 onEditorAction 而第一个执行。阻止它执行代码的第二个不同之处是什么?注意:代码中只有其中一个存在,而不是两者都存在。

// This one works    
this.setOnEditorActionListener { v, actionId, event ->
        if(actionId == EditorInfo.IME_ACTION_SEARCH){
            mOnRunSearchCallback()
            true
        } else {
            false
        }
    }

// This one does not work
    this.setOnEditorActionListener(object : TextView.OnEditorActionListener {
        override fun onEditorAction(v: TextView, actionId: Int, event: KeyEvent): Boolean {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                mOnRunSearchCallback()
                return true
            }
            return false
        }
})

标签: androidkotlin

解决方案


用这个改变第二个例子

this.setOnEditorActionListener(object : TextView.OnEditorActionListener {
      override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
             return true;
      }
 })

基本上,你有错误的参数类型 v 和事件v&event都是可以为空的。


推荐阅读