Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggling visibility in Kotlin, isVisible unresolved reference

Slowly learning Kotlin. Just generating a random number from a roll. If roll = 9 I want to make the button and seekbar invisible.

I'm using the toggleVisibility function to accomplish this, but the Kotlin compiler sees isVisible as a unresolved reference

package com.example.randomizer

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import android.widget.VideoView
import java.util.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val rollButton = findViewById<Button>(R.id.rollButton)
        val resultsTextView = findViewById<TextView>(R.id.resultsTextView)
        val seekBar = findViewById<SeekBar>(R.id.seekBar)
        val winText = "9 You Win !"




        rollButton.setOnClickListener {
            val rand = Random().nextInt(seekBar.progress)
            resultsTextView.text = rand.toString()
            if (rand == 9) {
                resultsTextView.text = winText
                seekBar.toggleVisibility()
                rollButton.toggleVisibility()
            }

        }



    }

    fun View.toggleVisibility() {
        if (this.isVisible()) {
            this.visibility = View.INVISIBLE
        } else {
            this.visibility = View.VISIBLE
        }
    }
}

Compiler error:

unresolved reference isVisible
like image 834
Rob Avatar asked Dec 05 '22 09:12

Rob


1 Answers

As others mentioned above, you can either specify isVisible() as an extension function by yourself.

fun View.isVisible() = this.visibility == View.Visible

Or you can add the KTX view dependency and start using some of the methods there. I recommend you have a look at: https://developer.android.com/reference/kotlin/androidx/core/view/package-summary#(android.view.View).isVisible:kotlin.Boolean

To import and start using KTX add to your Dependencies in build.gradle

implementation "androidx.core:core-ktx:1.0.2"

KTX is a set of Kotlin extensions that are commonly used. Check also: https://developer.android.com/kotlin/ktx

like image 176
Giorgos Neokleous Avatar answered Apr 15 '23 08:04

Giorgos Neokleous