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

时间:2021-01-20 20:06:22

I have this code to implement a listener for a Range Bar library:

我有这段代码来实现Range Bar库的监听器:

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

    });

Now I've tried to import it and change it to kotlin in the following ways:

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

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

or

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

In both cases, the app crashes with the following error:

在这两种情况下,应用程序都崩溃并出现以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.appyvet.materialrangebar.RangeBar.setOnRangeBarChangeListener> (com.appyvet.materialrangebar.RangeBar$OnRangeBarChangeListener)' on a null object reference

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

What am I doing wrong?

我究竟做错了什么?

1 个解决方案

#1


2  

Your rangebar is null,

您的范围栏为空,

To avoid crash, use like this :

为避免崩溃,请使用如下:

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

or

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

#1


2  

Your rangebar is null,

您的范围栏为空,

To avoid crash, use like this :

为避免崩溃,请使用如下:

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

or

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