谷歌I/O大會公佈Kotlin成爲了android的官方開發語言,並且有不少大牛說Kotlin的各種好,那就試試唄
1.首先是安裝插件:File-Settings-Plugins搜索Kotlin,如果沒有結果可以點擊查找。
之後會彈出兩個框選擇Kotlin版本,選擇相應的版本(一般會自動選擇)直接ok。
2.安裝完成之後在新建類是就會出現如圖:
3.gradle配置,Kotlin插件加入以後gradle文件發生了改變,需要增加一些配置才能方便使用:
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultConfig { applicationId "com.example.administrator.refreshrecycleview" minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } buildscript { repositories { jcenter() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.1.0' testCompile 'junit:junit:4.12' compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" } repositories { mavenCentral() }4.Kotlin集成完畢使用時,注意導入
import android.os.Bundle import android.support.v7.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* /** * Created by Administrator on 2017/6/9. */ class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initView() initData() } private fun initView() { change_btn.setOnClickListener { main_tv.text = "Hello Kotlin" } } private fun initData() { } }activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/main_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> <Button android:id="@+id/change_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/main_tv" android:text="change" /> </RelativeLayout>main_tv是TextView的id,再也不用findviewById了。