Android studio - MainActivity.kt cant access id

Viewed 1170

cant access id attribute in the mainActivity.kt i have tried : 1. clean project on the build menu 2. rebuild project on the build menu 3. FILE-> invalidate cache and restart

<Button
        android:id="@+id/decidebtn"
        style="@style/Widget.AppCompat.Button.Borderless.Colored"
        android:layout_width="407dp"
        android:layout_height="56dp"
        android:background="@color/black"
        android:text="Decide!"
        android:textColor="@color/white"
        android:textSize="18sp"
        app:backgroundTint="@color/teal_700"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />



import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

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

    decidebtn.setOnClickListener{

    }


}

}

4 Answers

It's deprecated Base on the google document

Kotlin Android Extensions is deprecated, which means that using Kotlin synthetics for view binding is no longer supported.

Use View Binding instead of Kotlin synthetic

If you want to access widget in code then you need to enable databinding in build.gradle file :

 dataBinding {
    enabled = true
}

you need to define layout tag in XMl and following code in JAVA:

class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
   super.onCreate(savedInstanceState)
  MainActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

 }

Don't forget to add in app/build.gradle:

apply plugin: 'kotlin-android-extensions'

Then import layout package in MainActivity file

Yes, kotlin synthetics is deprecated but still it is good enough in a small project

I think you should import your XML file (XML path.activity_main*)

Related