3

I have code:

package com.example.admin.maytinh

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.example.admin.maytinh.R.id.button
import com.example.admin.maytinh.R.id.editText
import com.example.admin.maytinh.R.id.editText2
import com.example.admin.maytinh.R.id.editText3


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button.setOnClickListener(View.OnClickListener{xuly()})
    }

    public fun xuly(){
        val a:Int = editText.text.ToString().ToInt()
        val b:Int = editText2.text.ToString().ToInt()
        val c:Int = a + b
        editText3.text = c.ToString()
    }

}

When i run it, i receive errors:

  • unresolved reference setOnClickListener
  • unresolved reference: text
  • unresolved reference: ToString

Anyone can explain for me why this is so and fix it Thank you

4 Answers4

12

You importing ids, not views. Instead of:

import com.example.admin.maytinh.R.id.button
import com.example.admin.maytinh.R.id.editText
import com.example.admin.maytinh.R.id.editText2
import com.example.admin.maytinh.R.id.editText3

use this:

import kotlinx.android.synthetic.main.activity_main.*

and add plugin in app gradle file:

apply plugin: 'kotlin-android-extensions'
Alex Nik
  • 753
  • 6
  • 15
4

You got unresolved error because you have not imported view. Instead of view you have imported ids.

There import To import single view

import kotlinx.android.synthetic.main.<layout_name>.<view_name>;

or

To import all widget properties for a specific layout

import kotlinx.android.synthetic.main.<layout>.*

Also you need is to enable the Android Extensions Gradle plugin in your module's build.gradle file:

apply plugin: 'kotlin-android-extensions'
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
2

It looks like you're trying to use Kotlin Android Extensions. To do so import:

import kotlinx.android.synthetic.main.activity_main.*

instead of

import com.example.admin.maytinh.R.id.button
import com.example.admin.maytinh.R.id.editText
import com.example.admin.maytinh.R.id.editText2
import com.example.admin.maytinh.R.id.editText3

Spend few minutes on reading how KAE work - it will help you a lot.

Moreover, there are no such methods as ToString() and ToInt(). What you're looking for is this: toString() and toInt().

rafal
  • 3,120
  • 1
  • 17
  • 12
0

I faced the same problem even after using migrating to viewBinding. It turns out that the problem was that I mistakenly gave my webview the same XML id then the layout it was in. I spent a weekend trying to solve it. I guess sharing that will be useful for someone else.

enter image description here