Listen to the use of kotlin can find the control without findviewbyid, Xiaosheng can't wait to try, the result... Without a careful look at the official documents, we are inexperienced and in a hole.
Direct use of tv.text assignment, prompt can not find tv.... Check it online and import it.<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.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="com.example.miracle.kotlindemo.MainActivity"> <TextView android:id="@+id/tv" //Add an id 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" /> </android.support.constraint.ConstraintLayout>
The results suggest that kotlinx cannot find...import kotlinx.android.synthetic.main.activity_main.*;
package com.example.miracle.kotlindemo import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.*; class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //val tv=findViewById(R.id.tv) as TextView; tv.text="Hello Kotlin"; } }
After searching the Internet for half a day, I tried several solutions and found a solution in the official documents.
Add in build.gradle(Module: app)
apply plugin: 'kotlin-android-extensions'
Okay, by default only kotlin-androidI don't know why the government doesn't tacitly add this...