1

I make an ear training app and want the levels to be customizable. So I have a class with the same function for each of the 12 tones, so imagine setDb, setD, setEb etc.:

class MakeLevel(context: Context) {
    fun setC(something: Boolean): Boolean {
        var c = something
        return c
    }

I then instantiate the class in my main activity (FullscreenActivity):

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_fullscreen)
    makeLevel = MakeLevel(this)
}
companion object {
    lateinit var makeLevel: MakeLevel
}

Then in the fragment where the levels are selected, I do this:

override fun onResume() {
    super.onResume()
    majpentlevelbutton.setOnClickListener { view ->
        FullscreenActivity.makeLevel.setC(true)
        // [same for setD, setE, setG and setA, and false for all the other notes]
        view.findNavController().navigate(R.id.action_levelSelectFragment_to_chromaticFragment)
    }
}

Now here comes my problem: I want to access the value of c to determine whether ther sounds and the button for c should be loaded or not, and I can´t find a way to do so. For example, I´d like to use it like this:

if (c == true) {
    c_button.visibility = View.VISIBLE
}
else {
    c_button.visibility = View.GONE
}

I´ve tried c, makeLevel.c, FullscreenActivity.makeLevel.c and many more. Every time I get an Unresolved reference. So my question is how do I get a reference on the var c?

2 Answers 2

2

So far c is only a local variable within the method setC. If you need the value outside of the method you need to define a property:

class MakeLevel(context: Context) {
    var c = initValue
    fun setC(something: Boolean){
        c = something
    }
}

Now you can access this variable with: FullscreenActivity.makeLevel.c

Sign up to request clarification or add additional context in comments.

1 Comment

Note: in this case there's no point to having a setC method, you just write FullscreenActivity.makeLevel.c = whatever.
0

Your problem is that you are trying to access a variable outside of its scope.

class MakeLevel(context: Context) {
    private var c = initValue

    fun setC(something: Boolean){
        c = something
    }

    fun getC(something: Boolean) {
        return c
    }

    if (getC() == true) 
        c_button.visibility = View.VISIBLE
    else 
       c_button.visibility = View.GONE
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.