Search code examples
javaandroidkotlinandroid-layoutandroid-constraintlayout

Switch to Display ConstrainedLayout not working


I am trying to build a simple Android switch (availabilitiesSwitch) t display the content of a Constrained Layout.

The switch looks like this:

<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" />

and the code in the Fragment is such:

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

        (activity as BaseActivity).run {

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

        }
    }

where showShifts is as follows (setupAvailabilities is the constrained layout I want to toggle):

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

Currently, availabilitiesSwitch is evaluated to null. Can anyone think of a reason?


Solution

  • Move your logic to onViewCreated function, availabilitiesSwitch should be not null there:

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        (activity as BaseActivity).run {
    
            availabilitiesSwitch?.setOnCheckedChangeListener { buttonView, isChecked ->
                if(isChecked) {
                    showShifts()
                }
            }
        }
    }