Kotlin筆記一,配置Android Studio

創建項目並在根目錄 build.gradle 配置

buildscript {
    ext.kotlin_version ='1.3.11'

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

在 app 中的 build.gradle 配置

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
}

然後編譯成功即可使用。

創建Activity
在這裏插入圖片描述
選擇語言爲Kotlin

在這裏插入圖片描述
佈局文件寫法不變

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".ui.KotlinActivity">
    
    <TextView 
        android:id="@+id/tv_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="hello"
        />

</LinearLayout>

Activity中可以直接通過id去賦值,省去了findViewById的操作。

package com.example.textkt.ui

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.example.textkt.R
import kotlinx.android.synthetic.main.activity_kotlin.*

class KotlinActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin)
        
        tv_text.text = "Kotlin NB"
    }
}

運行效果
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章