I try to create a new project in Android Studio (AS) 4.1 with Kotlin. I use "empty activity" and create project "MyTest" .
AS creates activity_main.xml with unnamed TextView "Hello World". I give the id the name myText.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/myText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
The created MainActivity.kt is standard and looks like this
package com.example.mytest
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)
}
}
All this is normal AS, BUT
now in MAinActivity.kt it should be possible to type
myText = "any string"
but here myText is not recognised. And I don't understand that.
I have some small test-projects from earlier AS version. They look identical - and it works to type myText and myText is immediatly recognized.
What is wrong with my coding or project creation! Having created several projects and compared with former projects, I see no fault with my doing. Who has an idea?
You need to integrate Kotlin Android Extensions in your project in order to you have your views recognized like that. Just add the following lines in your build.gradle
:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
More info in this article: https://antonioleiva.com/kotlin-android-extensions/
synthetic will be deprecated in Kotlin 1.4.20, https://youtrack.jetbrains.com/issue/KT-42121 due to not being null-safe. If you are going to maintain the project you are building for a awhile it will be batter not to use Kotlin Android Extensions.
Suggested alternatives in the link above are:
FindViewById is the 'official' method and it's easy to use, Kotlin suggests ViewBinding which has some boilerplate as I read (I haven't used it yet).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With