Kotlin annotation parameter must be a compile-time

2019-06-22 10:22发布

问题:

@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.

回答1:

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")
}