0

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?

Sergio
  • 27,326
  • 8
  • 128
  • 149
ksenia
  • 187
  • 7
  • 23
  • In a Fragment, Views are not inflated in onCreate(). They will be inflated in onCreateView(), so this is the earliest possibility to access them See also the [documentation for Fragment](https://developer.android.com/guide/components/fragments) – Bö macht Blau Feb 25 '19 at 20:13
  • Possible duplicate of [NullPointerException accessing views in onCreate()](https://stackoverflow.com/questions/23653778/nullpointerexception-accessing-views-in-oncreate) – Bö macht Blau Feb 25 '19 at 20:14

1 Answers1

1

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()
            }
        }
    }
}
Sergio
  • 27,326
  • 8
  • 128
  • 149