Android Studio 下的Kotlin HelloWorld

一、Android Studio下Kotlin環境配置

Kotlin的一輪浪潮迅猛撲過來,藉助這個風口,先多學習學習。

【某人說,在風口,豬也能飛起來。笨鳥先飛羅 ~_~】


1,安裝Kotlin的相關插件

執行 Settings -> plugins -> BrowseRepositories中搜索“Kotlin”
安裝kotlin插件。


【關於是否安裝Kotlin Extensions不同博客有不同說明,實際測試中沒有安裝也可行】

2,新建Kotlin Activity



3,配置Kotlin Configure



配置成功後,在Module下的Build.gradle中有添加內容:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "com.future.customcontrolsfirstdemo"
        minSdkVersion 11
        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'
        }
    }
}

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.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}
repositories {
    mavenCentral()
}
項目路徑下的Build.gradle也有添加內容:

buildscript {
    ext.kotlin_version = '1.1.51'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        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
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
經過編譯後,項目應該能夠正常運行。


4,HelloWorld的具體實現

xml文件大體和原先項目一致:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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.future.customcontrolsfirstdemo.Main2Activity">

    <TextView
        android:id="@+id/kotlin_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:text="Hello Kotlin !!!"
        android:textColor="#ff0000"
        android:textSize="32sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.027"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.047" />


</RelativeLayout>

Activity中的實現:

class Main2Activity : AppCompatActivity(), View.OnClickListener {
    private var textView: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)

        textView = findViewById(R.id.kotlin_tv) as TextView
        textView!!.text = "hello kotlin!"
    }

}

是的,如此,就算是踏入Kotlin的大門了吧,或許早了點,看見門了。。。。



二、Kotlin HelloWorld的擴展實現

如上邊實例所表述,XML沒有什麼變化,控件的實例化沒有什麼變化,控件的使用也沒有什麼變化。那Kotlin爲何能夠迅速推廣開來呢?

我們做點小小的改動,初窺門徑。

Module下Build.gradle頂部添加:

apply plugin: 'kotlin-android-extensions'


在類的實現中添加:
import kotlinx.android.synthetic.main.activity_main.*


其中activity_main是指XML的名稱。
有那麼一點神奇的事情發生了,我們不需要findViewByID();


class Main2Activity : AppCompatActivity(), View.OnClickListener {
    private var textView: TextView? = null
    var t: Toast? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)

        textView = findViewById(R.id.kotlin_tv) as TextView
        textView!!.text = "hello kotlin!"

        btn1.setOnClickListener(this)
        btn2.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn1 -> Toast.makeText(this@Main2Activity, "${btn1.text}", Toast.LENGTH_SHORT).show()
            R.id.btn2 -> if (t == null) {
                Toast.makeText(this@Main2Activity, "${btn2.text}", Toast.LENGTH_SHORT).show()
            } else {
                t?.setText("${btn2.text}")
                t?.show()
            }
        }
    }

}




三、細節擴展
在Android Studio編譯工具下,安裝插件以後,能夠將之前的Java文件進行轉換成爲Kotlin代碼。



面對一個新事物,我們應該學習和接納他,同時也需要省視他。推薦一篇文章,也是給自己做一個標記:
http://www.jianshu.com/p/f364e3f9cc36   Kotlin --這次入門就不用放棄了 



一個迷茫階段,沒有把自己直接提升一個境界的好方法,也不確信在未來能夠有更好的處理辦法。甚至於覺得自己並不是那種聰明的人,在這一片沼澤地裏,迷失方向的小孩只有:適當的堅持鍛鍊,維持一個還不錯的身體;繼續在自己所選擇的路上慢慢積累,儘管那麼的不明顯,收效相對的微小。


發佈了121 篇原創文章 · 獲贊 32 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章