【问题标题】:Button doesn't set to Enabled even after "if conditions" are met即使满足“如果条件”,按钮也不会设置为启用
【发布时间】:2020-05-23 15:07:52
【问题描述】:

下面的代码应该将按钮的“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}

    }
}

【问题讨论】:

    标签: android if-statement kotlin


    【解决方案1】:

    onCreate() 是您活动中的生命周期方法。它仅在第一次调用您的 Activity 或手机配置更改时调用,例如屏幕旋转、区域设置更改和...

    在 onCreate 中设置 if (epilegmenoi.size == 2) {ok_button.isEnabled=true} 对您没有任何作用。

    考虑将这行代码移到某个基于事件的函数中。

    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()
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多