Home > database >  Enable/Disable buttons in fragment for Kotlin
Enable/Disable buttons in fragment for Kotlin

Time:12-22

I am trying to add a function to enable/disable some buttons in my fragment, however I am getting a compilation error

"Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable reciever"

I have tried a couple of different methods; from calling the button directly, to calling the activity where I would do the button work, but I get the same error:

private fun enableButtons(buttonState: Boolean) {
    (activity as MainActivity?).enableButtons(buttonState)
    //                         ^ error there
}

and

    var button = activity.findViewById(R.id.button0) as Button
    //                   ^ error here
    button.isEnabled = false
    button.isClickable = false

I'm pretty new to Kotlin and can't work out how can I access the buttons without passing in a view

CodePudding user response:

Well, it is kinda suggesting what you have to do:

"Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable reciever"

Means that whatever variable you are using, might be null. So if you tried running

(activity as MainActivity?).enableButtons(buttonState)

this might end up as:

null.enableButtons(buttonState)

which (you may already know) will cause a crash

All kotlin is asking for is an alternative (when the variable is in fact null) or a "promise" that the variable is not null (!!)

A simple fix would be just to use:

(activity as MainActivity?)!!.enableButtons(buttonState)

or just remove ? after MainActivity

(more on .? and !! you can find here: What's the difference between !! and ? in Kotlin?)

CodePudding user response:

Remove ? and add !!.

It means you are saying that MainActivity can not be null

(activity as MainActivity?)!!.enableButtons(buttonState)
  • Related