android studio 3.0 preview 使用kotlin写android,抛弃findviewbyid

来源:互联网 发布:淘宝开店会员名大全 编辑:程序博客网 时间:2024/05/17 02:09

听所使用kotlin就可以不用findviewbyid来找控件了,小生迫不及待的尝试了一下,结果。。。没仔细看官方文档,经验不足,掉坑里了难过

<?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"  //添加一个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>
直接使用tv.text赋值,提示找不到tv。。。网上查了一下,需要导入
import kotlinx.android.synthetic.main.activity_main.*;
结果提示kotlinx找不到。。。
package com.example.miracle.kotlindemoimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport 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";    }}

网上找了半天,尝试了几种方案也没解决,最后在官方文档中找到解决方法

在build.gradle(Module: app)中添加

apply plugin: 'kotlin-android-extensions'
就可以了,默认只有kotlin-android难过,不懂官方为什么不默认把这个加上。。。


原创粉丝点击