android studio 3.0 preview uses kotlin to write android, discarding findviewbyid

Keywords: Android xml encoding Gradle

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.

<?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>
Direct use of tv.text assignment, prompt can not find tv.... Check it online and import it.
import kotlinx.android.synthetic.main.activity_main.*;
The results suggest that kotlinx cannot find...
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...


Posted by SycoSyco on Tue, 12 Feb 2019 01:12:20 -0800