Kotlin 開發(fā)Android (四):提升Android開發(fā)效率

1.去掉findViewById

只需要在App Module的build.gradle 中添加
apply plugin: 'kotlin-android-extensions'//手動添加
代碼然后就可以這樣寫

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin)
        //直接使用activity_kotlin.xml中的id
        test.setOnClickListener { view-> onClickTest(view) }
    }

inflate生成的View,也可以直接操作xml中id

    fun onClickTest(view: View):String?{
        var view:View   = LayoutInflater.from(this).inflate(R.layout.dialog_kotlin,null, false);
        val text:String = "clicked this is dialog!";
        message = text;
        view.message.setText(message);
        var dialog: AlertDialog = AlertDialog.Builder(this).setView(view).setPositiveButton("this", DialogInterface.OnClickListener { dialog, which ->  onClickDialog(dialog, which, text)}).create();
        dialog.show();

        return null;
    }

2.空安全

i. 變量或參數(shù)可空用 ?標(biāo)記

不可空類型如果設(shè)置為空會提示錯誤


屏幕快照 2017-04-04 下午4.15.29.png
ii.安全調(diào)用

調(diào)用可空參數(shù)時未加?會提示不安全,?表示非空就返回后面的內(nèi)容,為空就返回null


屏幕快照 2017-04-04 下午4.23.52.png
iii. ?: 表達式

表達式左邊為非空,為空時‘執(zhí)行’表達式右邊,如右邊包含return ,throw Exception等也可以

var object1: StaticInnerClass? = null;
var length3: String = object1?.getNewName() ?: throw RuntimeException("test");
iiii. !! 非空強制轉(zhuǎn)換符
屏幕快照 2017-04-04 下午4.49.47.png

3.函數(shù)擴展

    //擴展Context類,增加toast方法
    fun Context.toast(message: String, time: Int) {
        Toast.makeText(this, message, time).show();
    }

    fun onClickTest(view: View):String?{
        var context: Context = this;
        context.toast("toast text",Toast.LENGTH_SHORT);//調(diào)用擴展方法
        return null;
    }

在外部擴展,供整個項目使用。新建Kotlin文件,內(nèi)容如下

package com.ifnoif.androidtestdemo.kotlin

import android.content.Context
import android.widget.Toast

/**
 * Created by shen on 17/4/4.
 */


fun Context.toast(message: String, time: Int) {
    Toast.makeText(this, message, time).show();
}

4.數(shù)據(jù)類(data class,巨幅 減少代碼)

data class會自動根據(jù)構(gòu)造函數(shù)實現(xiàn)equals()/hashCode,toString,還會增加copy方法

    data class Car(var name:String,var color:String, var weight:Int){
    }

    fun testCar(){
        var car:Car = Car("bus","red",1000);
        var color = car.color;
        var name = car.name;
        var weight = car.weight;
        var newCar:Car =car.copy(name="bicycle",weight = 10);
        var equalsResult =car.equals(newCar);
        
    }

5. lambda 表達式,減少匿名內(nèi)部類

看看setOnClickListener怎么寫的

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

        test.setOnClickListener { view-> onClickTest(view) }
    }

更多Lambda用法參考:函數(shù)式編程之Lambda表達式

6.Anko 庫,可以讓您編寫描述性的布局,而無需使用XML

如在activity中顯示一個垂直布局

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState) {
        verticalLayout {
            val name = editText()
            button("Say Hello") {
                onClick { toast("Hello, ${name.text}!") }
            }
        }
    }
}

需要配置插件

dependencies {
    compile 'org.jetbrains.anko:anko-sdk15:0.7.1' // sdk19, sdk21, sdk23 are also available
    compile 'org.jetbrains.anko:anko-support-v4:0.7.1' // In case you need support.v4 bindings
}

更多Anko相關(guān):https://github.com/Kotlin/anko

7.其他特性

Smart Casts(智能類型轉(zhuǎn)換)

if (obj is String) {
    //判斷通過后就能使用該類型的API
    print(obj.length)
}

//安全的類型轉(zhuǎn)換,類型不匹配則x為null
var y: Any = 123
val x: String? = y as? String
println("x:"+x+" y:"+y)//輸出x:123 y:null

String Templates(字符串模板)

//更容易閱讀
val s = "abc"
val str = "$s.length is ${s.length}" // 結(jié)果"abc.length is 3"

代理

//接口中包含具體的方法,類似java8中Default 方法
interface Operation {
    fun add(a: Int, b: Int): Int;
    fun print(){
        println("Operation")
    }
}

Range expressions(范圍表達式)

for (i in 1..4) print(i) // prints "1234"
for (i in 4..1) print(i) // prints nothing
for (i in 4 downTo 1) print(i) // prints "4321"
for (i in 1..4 step 2) print(i) // prints "13"
for (i in 4 downTo 1 step 2) print(i) // prints "42"

具體方法重寫成抽象方法

open class Base {
    open fun f() {}
}

abstract class Derived : Base() {
    override abstract fun f()
}

class SubDerived:Derived() {
    override fun f() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

8.不支持的

異常檢查

拋出異常后不會讓你強制捕獲異常。kotlin也支持在方法上拋出異常@Throws(Exception::class)
如果java調(diào)用該方法需要強制處理

//kotlin調(diào)用java中有異常的方法
var fileOutputStream:FileOutputStream = FileOutputStream("/out.txt")
var byteArr:ByteArray = ByteArray(1024)
fileOutputStream.write(byteArr)
//kotlin定義一個會拋出異常的方法
companion object {
        @Throws(Exception::class)
        fun testGson() {companion object {
        @Throws(Exception::class)
        fun testGson() {
        }
}

//java中調(diào)用kotlin中方法
public void testInvokeKotlin() {
        try {
            GsonTest.Companion.testGson();
        } catch (Exception e) {
            e.printStackTrace();
        }
}

更多與java比較
https://kotlinlang.org/docs/reference/comparison-to-java.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容