我有这段代码可以实现 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)
我在做什么错了?
答案 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"
}