简体   繁体   English

Kotlin:实例化类中变量的未解析引用

[英]Kotlin: Unresolved Reference for variable from instantiated class

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.: 因此,我有一个具有相同功能的类,分别针对12种音调,因此可以想象一下setDb,setD,setEb等:

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

I then instantiate the class in my main activity (FullscreenActivity): 然后,在我的主要活动(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. 现在出现了我的问题:我想访问c的值以确定是否发出声音以及是否应加载c的按钮,而我找不到解决方法。 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. 我已经尝试过cmakeLevel.cFullscreenActivity.makeLevel.c等。 Every time I get an Unresolved reference . 每次获得Unresolved reference So my question is how do I get a reference on the var c? 所以我的问题是如何获得var c的参考?

So far c is only a local variable within the method setC . 到目前为止, c只是方法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 现在,您可以使用以下命令访问此变量: FullscreenActivity.makeLevel.c

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 } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM