切换到显示约束布局不起作用

问题描述 投票:0回答:1

我正在尝试构建一个简单的Android开关(可用性开关)来显示约束布局的内容。

开关看起来像这样:

<Switch
            android:id="@+id/availabilitiesSwitch"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="24dp"
            android:layout_marginEnd="16dp"
            android:showText="false"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

并且片段中的代码是这样的:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        (activity as BaseActivity).run {

            availabilitiesSwitch?.let {
                it?.setOnCheckedChangeListener { buttonView, isChecked ->
                    if(isChecked) {
                        showShifts()
                    }
                }
            }

        }
    }

其中showShifts如下(setupAvailabilities是我要切换的约束布局):

fun showShifts() {
    setupAvailabilities.visibility = View.VISIBLE
}

目前,availabilityswitch被评估为null。谁能想到一个原因?

java android kotlin
1个回答
1
投票

将你的逻辑移动到onViewCreated函数,availabilitiesSwitch应该不为null:

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    (activity as BaseActivity).run {

        availabilitiesSwitch?.setOnCheckedChangeListener { buttonView, isChecked ->
            if(isChecked) {
                showShifts()
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.