1.执行 Settings -> plugins -> BrowseRepositories中搜索“Kotlin”
安装后重新启动就可以了
配置完成之后在主项目的跟build.gradle中完成以下配置:
buildscript {
ext.kotlin_version = '1.0.4'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
会多出这样两样代码,而在module的build.gradle中:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
android {
...
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
...
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
很简单有木有
class MainActivity : AppCompatActivity() {
private var mIndicatorView: ImageView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initView()
}
private fun initView() {
mIndicatorView = findViewById(R.id.image) as ImageView
}
}
Android Studio中还有一个关于Kotlin很实用的操作,就是将Java源代码转化为Kotlin代码:
Kotlin插件能将Java转换为Kotlin类. 我们可以轻松的通过‘Code’菜单中的‘Convert Java File to Kotlin File'选项转换当前的Activity到Kotlin类