简体   繁体   中英

Unresolved Reference using Kotlin for android

I am getting Unresolved Reference when compiling

Error:(42, 26) Unresolved reference: r1 Error:(42, 36) Unresolved reference: ds

in the onClick method variables r1, and ds are shown to be in errors. in kotlin all varibales are final. so how come it is not accepting it. please advice following is the script

class MainActivity : AppCompatActivity(), View.OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val b1: Button = findViewById(R.id.add)

        val a1: EditText = findViewById(R.id.opr1)
        val a2: EditText = findViewById(R.id.opr2)

        val d1: Int = (a1.getText().toString().toInt())
        val d2: Int = (a2.getText().toString().toInt())

      var r1: TextView = findViewById(R.id.res)
        var ds :Int =d1+d2


    }

    override fun onClick(v: View?) {

        when (v?.id) {

            R.id.add ->  r1.text= (ds).toString()

        }
    }
}

ds is local variable that can only be accessed within the function onCreate() . If you want to sum up the numbers of the EditText , you should put your addition logic inside the onClick() method:

override fun onClick(v: View) {
    when (v.id) {
        R.id.add -> {
            val d1: Int = et1.text.toString().toInt()
            val d2: Int = et2.text.toString().toInt()
            val ds = d1 + d2
            r1.text = ds.toString()
        }
    }
}

Also, you should declare r1 and other view reference as class member so that they can be accessed within your Activity class but not only onCreate() .

r1 is a local variable in onCreate so it's not accessible outside of this function.

Declare it outside of the function like so:

private lateinit var r1: TextView

Assign it in onCreate like so:

r1 = findViewById(R.id.res)

Then you can access it as you expect:

r1.text= ds.toString()

The same rule applies for other variables you want to access outside of onCreate .

Why lateinit

onCreate is not a constructor so r1 is uninitialized before that. But you know that onCreate is the first thing called in the activity lifecycle so when you initialize the variable here it will always be non-null.

Otherwise you'd have to declare the variable like this:

private var r1: TextView?

and access it with the !! operator, for example:

r1!!.setText(...)

The variable ds only exists into the first function. You must declare it outside to access it from the second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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