即使满足“条件”,按钮也不会设置为“启用”

下面的代码应该将按钮的“ isEnabled”属性设置为true,但事实并非如此。 我初始化了一个可变列表,该列表在某些开关打开时添加一个字符串,并在关闭时删除它们。

我创建了一个if条件,如果列表的大小等于2,则启用ok_button。 即使满足条件,我也看不到为什么ok_button没有更新。

package com.example.malakes
import android.nfc.Tag
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.CompoundButton
import android.widget.Switch
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import android.util.Log
import android.view.View
import android.widget.Button

class MainActivity : AppCompatActivity() {

companion object{ const val TAG = "MyActivity" } //define TAG

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

    val epilegmenoi: MutableList<String> = mutableListOf()

    val tony = findViewById<Switch>(R.id.switchTony)
    val giorgis = findViewById<Switch>(R.id.switchGiorgos)
    val duke = findViewById<Switch>(R.id.switchDuke)
    val nikolas = findViewById<Switch>(R.id.switchNikolas)
    val dionisis = findViewById<Switch>(R.id.switchDionisis)
    val grigoris = findViewById<Switch>(R.id.switchGrigoris)
    val ok_button = findViewById<Button>(R.id.buttonOK)
    val clear_button = findViewById<Button>(R.id.buttonCLEAR)

    tony.setOnCheckedChangeListener { _, isChecked ->
        if (isChecked) {
            epilegmenoi.add("Tony")
        } else {
            epilegmenoi.remove("Tony")
        }


    }
    giorgis.setOnCheckedChangeListener { _, isChecked ->
        if (isChecked) {
            epilegmenoi.add("Giorgis")
        } else {
            epilegmenoi.remove("Giorgis")
        }


    }

    if (epilegmenoi.size == 2) {ok_button.isEnabled=true}

}

}

评论
ciste
ciste

onCreate() is a Lifecycle method in your activity. It is only called when your Activity is being called for the first time or when phone configs change, e.g. Screen Rotation, Locale change, and ...

Setting if (epilegmenoi.size == 2) {ok_button.isEnabled=true} inside onCreate doesn't do anything for you.

考虑将这行代码移至某些基于事件的函数。

fun updateButtonState() {
    my_button.isEnabled = (myList.size == 2)
}

在您的复选框事件内:

tony.setOnCheckedChangeListener { _, isChecked ->
    if (isChecked) {
        epilegmenoi.add("Tony")
    } else {
        epilegmenoi.remove("Tony")
    }
     updateButtonState()
}

giorgis.setOnCheckedChangeListener { _, isChecked ->
    if (isChecked) {
        epilegmenoi.add("Giorgis")
    } else {
        epilegmenoi.remove("Giorgis")
    }
    updateButtonState()
}
点赞
评论