Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin annotation parameter must be a compile-time constant

Tags:

android

kotlin

@BindView(R.id.et_login_username)
internal var loginUsername: EditText? = null

Kotlin annotation parameter must be a compile-time constant

This is the error that's showing.

like image 283
Ankit Sharma Avatar asked Mar 22 '18 07:03

Ankit Sharma


1 Answers

To use ButterKnife in Kotlin, make sure you have added the following dependencies in app gradle.

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'

dependencies {

    implementation 'com.jakewharton:butterknife:latest-version'

    // use kapt for kotlin
    kapt 'com.jakewharton:butterknife-compiler:latest-version'
}

In your activity, declare views using lateinit to avoid compile-time constant error:

@BindView(R.id.et_login_username)
lateinit var loginUsername: EditText

Moreover, Kotlin developers also introduced an alternative for binding android views which eliminates findViewById calls. Its known as Kotlin Android Extensions,

To use this:

In app's build.gradle, add this plugin

apply plugin: 'kotlin-android-extensions'

In Activity,

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

class MainActivity : AppCompatActivity() {

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

       // All views can be used directly with their id declared in the xml
       et_login_username.setText("Hello")
}
like image 151
Faraz Avatar answered Oct 06 '22 22:10

Faraz