Why does it still say "Unresolved reference: button" even when I have button id in xml?

Viewed 2815

I have simple android app, and I want to click button to pass other activity. But it says

Unresolved reference: button

even I give id in xml. I do not know where I mistake.

Screenshot:

enter image description here

activity_main.xml:

   <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:text="Click"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

main_activity:

class MainActivity : AppCompatActivity() {

companion object {
const val USER = "user"
 }

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val user = User( "mayk",   "qqqq", PersonalInfo("mayk", "james"))


    button.setOnClickListener{
        val intent = Intent (this, Activity2::class.java)
        intent.putExtra(USER, user)
        startActivity(intent)
    }
   }
   }
3 Answers
val button = findViewById<View>(R.id.button)

why still say “Unresolved reference: button” even I have button id in xml?

The ids in your xml layout files are not Kotlin variables. You need to declare a variable val button before you can use it. You also need to initialize the variable to refer to a Button object. One way to do that is with

val button = findViewById<View>(R.id.button)

I suggest that you read the beginner guides at https://d.android.com to understand the fundamentals of Android programming.

No need to use findViewById()

Go to your Build.Gradle (Module: app) Add the following line

apply plugin: 'kotlin-android-extensions'

or

id 'kotlin-android-extensions'

Then it will ask you to sync Then press sync After it will ask you to import that only by using ALT+ENTER

UPDATE : THIS SOLUTION IS DEPRECATED

now you have to use View Binding

set the viewBinding build option to true in the module-level build.gradle file

android {
...
buildFeatures {
    viewBinding true
    }
}

To set up an instance of the binding class for use with an activity, perform the following steps in the activity's onCreate() method:

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ResultProfileBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
}

You can now use the instance of the binding class to reference any of the views:

binding.name.text = viewModel.name
binding.button.setOnClickListener { viewModel.userClicked() }

For more information you can have a look at https://developer.android.com/topic/libraries/view-binding

Related