您的位置:首页 > 移动开发 > Android开发

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

2017-05-20 12:24 716 查看
听所使用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.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";
}
}


网上找了半天,尝试了几种方案也没解决,最后在官方文档中找到解决方法
在build.gradle(Module: app)中添加

apply plugin: 'kotlin-android-extensions'

就可以了,默认只有kotlin-android,不懂官方为什么不默认把这个加上。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android studio kotlin