当下谷歌将Android的开发语言由java转变为Kotlin语言,当然在国内两三年的时间内应该是没什么大的影响,但是随着以后的迁移,肯定还是慢慢的转到Kotlin 上,每周抽点时间学习一下并不是坏事,大家还是慢慢的适应市场吧。现在开干起来。
当前的AS版本3.4默认支持Kotlin的,你不在需要繁琐的kotlin环境的配置了,直接干。
首先,我们任何开发语言都是建一个helloworld工程,还是一样,我也建立一个,然后,我只是在代码中设置一下文本,kotlin 避免了一堆的findViewbyId()拿到控件了,大大的简化了流程,布局 还是和以前一样的写,代码风格却有很大的改变。,不废话,先上布局:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/tv" 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>
随后在MainActivity中开启我们的Kottin之旅了:
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) tv.text = "你好啊"; } }
注意一下我们的红色标记,建立工程后,会导入布局的import kotlinx.android.synthetic.main.activity_main.*包后,我们无需再去那控件,直接拿到控件的id操作,赋值就行了,这样减少了一堆的代码。运行结果如下:
好了,你的第一个Kotlin工程就完成了,快来尝试一下吧!下一章,我们学习Kotlin的基本语法了,一起来吧。