setOnClickListener不工作android kotlin

时间:2018-05-15 03:06:26

标签: android kotlin

我正在学习android和kotlin,而且我正在构建一个练习应用程序。当我运行我的代码时,按钮不起作用,我不知道为什么或我做错了/忘了添加。任何帮助表示赞赏!

我的xml代码:

 <Button
    android:id="@+id/solveBtn"
    android:layout_width="113dp"
    android:layout_height="65dp"
    android:layout_marginBottom="184dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:text="Solve" 
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.501"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/NumInput" />

和我的kt代码:     class MainActivity:AppCompatActivity(){

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    var num = NumInput.inputType.toInt()
    var answer = ansText

    fun solver (num1 : Int) {
        var div = 1
        var count = 0
        if ((num1 > 0) && (num1 < 2)){
            println("$num1 is a prime number!")
        } else{
            while (div < num1){
                if ((num1 % div) == 0){
                    div++
                    count++
                }else {
                    div++
                }
            }
        }
        if (count == 0) {
            answer.text = "$num1 is not a prime number"
        } else {
            answer.text = "$num1 is a prime number"
        }

    solveBtn.setOnClickListener{
        println("Hello")
        answer.clearComposingText()
        solver(num)
        }
    }
}

}

再次感谢您的帮助!

4 个答案:

答案 0 :(得分:5)

您的solveBtn.setOnClickListener位于solver函数中,该函数从未被调用过。只需将setOnClickListener称为一个大括号。

答案 1 :(得分:1)

您需要在setOnClickListener

之外设置solver(..)
fun solver (num1 : Int) {
    var div = 1
    var count = 0
    if ((num1 > 0) && (num1 < 2)){
        println("$num1 is a prime number!")
    } else{
        while (div < num1){
            if ((num1 % div) == 0){
                div++
                count++
            }else {
                div++
            }
        }
    }
    if (count == 0) {
        answer.text = "$num1 is not a prime number"
    } else {
        answer.text = "$num1 is a prime number"
    }
}

solveBtn.setOnClickListener{
    println("Hello")
    answer.clearComposingText()
    solver(num)
    }
}

答案 2 :(得分:0)

请像这样使用:

 backArrow.setOnClickListener {
            finish()
        }

答案 3 :(得分:0)

检查XML,有时在使用contraintLayout时,android:enabled="false"默认设置为false,将其设置为true或将其删除