简体   繁体   中英

Error "unresolved reference" in Kotlin Android

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

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'

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'

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() .

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.

在此处输入图像描述

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