无法将Java代码转换为Kotlin以实现OnChangeListener

时间:2018-09-27 15:42:45

标签: java android kotlin nullpointerexception

我有这段代码可以实现 Range Bar库的侦听器:

rangebar.setOnRangeBarChangeListener(new RangeBar.OnRangeBarChangeListener() {
        @Override
        public void onRangeChangeListener(RangeBar rangeBar, int leftPinIndex,
                                          int rightPinIndex, String leftPinValue, String rightPinValue) {
        }

    });

现在,我尝试通过以下方式将其导入并将其更改为kotlin:

rangebar.setOnRangeBarChangeListener(object: RangeBar.OnRangeBarChangeListener {
        override fun onRangeChangeListener(rangeBar:RangeBar, leftPinIndex:Int,
                                  rightPinIndex:Int, leftPinValue:String, rightPinValue:String) {
            textView.text = "$leftPinIndex"
        }
    })

rangebar.setOnRangeBarChangeListener { rangeBar, leftPinIndex, 
rightPinIndex, leftPinValue, rightPinValue -> 
textView.text = "$leftPinIndex" }

在两种情况下,应用程序都会崩溃并显示以下错误:

  

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void com.appyvet.materialrangebar.RangeBar.setOnRangeBarChangeListener>(com.appyvet.materialrangebar.RangeBar $ OnRangeBarChangeListener)

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您的 rangebar

为避免崩溃,请像这样使用:

rangebar?.setOnRangeBarChangeListener(object: RangeBar.OnRangeBarChangeListener {
    override fun onRangeChangeListener(rangeBar:RangeBar, leftPinIndex:Int, rightPinIndex:Int, leftPinValue:String, rightPinValue:String) {
        textView.text = "$leftPinIndex"
    }
})

rangebar?.setOnRangeBarChangeListener { rangeBar, leftPinIndex, rightPinIndex, leftPinValue, rightPinValue -> 
    textView.text = "$leftPinIndex" 
}