Kotlin技巧與自定義語法糖
kotlin,ktx,anko
kotlin官方中文站:http://www.kotlincn.net/docs/reference/basic-syntax.html
ktx google官網:https://developer.android.google.cn/kotlin/ktx
anko github地址:https://github.com/Kotlin/anko
kotlin數組使用
不用使用String[]; 需要使用arrayOf()
//1.數組和集合定義
val names = arrayOf<String>("2", "3")
val ages = listOf<Int>(1, 2, 3)
//訪問
names[0]
ages[0]
//MutableList()和List
使用if,when表達式簡化代碼
//2.使用if,when表達式返回值
val invalid = isInvalid(2)
val age = getAge("x")
private fun isInvalid(num: Int): Boolean =
if (num > 3) {
true
} else if (num > 2) {
false
} else {
false
}
private fun getAge(name: String): Int {
return when (name) {
"xx" -> 3
else -> 10
}
}
減少重載方法,使用參數默認值
//3.使用函數默認參數
createUser("xx", 3)
createUser("qq")
private fun createUser(name: String, age: Int = 18) {
}
steam式操作
//4.steam流式操作
ages.filter { it > 3 }.map { (it * 3).toString() }.forEach { print(it) }
kotlin內部類與嵌套類
//5.內部類和嵌套類
MainInterface().fetchContext().takeIf { it == this }
MainEntity().fetchContext().takeIf { it == null }
//inner內部類,持有外部實例,可以調用外部方法
inner class MainInterface {
fun fetchContext(): Context {
return this@MainActivity
}
}
//嵌套類,只是寫在一個文件裏面,和另寫一個文件沒區別
class MainEntity {
fun fetchContext(): Context? {
//報錯,找不到MainActivity實例
return this@MainActivity
return null
}
}
foreach break
//6.foreach
ages.forEach {
if (it > 3) {
for (name in names) {
if (name == "xx") {
continue
}
break
}
}
}
高階函數與lambda
//7.高階函數與lambda
AlertDialog.Builder(this)
.setTitle("提示")
.setMessage("有新版本升級@")
.setCancelable(true)
.setPositiveButton("確定") { dialog, _ ->
//跳轉頁面
dialog.dismiss()
}
.create()
.show()
val alertDialog = showDialog {
setTitle("提示")
setMessage("")
setCancelable(true)
setPositiveButton("確定") { dialog, _ ->
//跳轉頁面
dialog.dismiss()
}
}
val alertDialog1 = showDialog1 {
it.setTitle("提示")
it.setMessage("")
it.setCancelable(true)
it.setPositiveButton("確定") { dialog, _ ->
//跳轉頁面
dialog.dismiss()
}
}
private fun showDialog(block: AlertDialog.Builder.() -> Unit): AlertDialog {
val builder = AlertDialog.Builder(this)
block.invoke(builder)
val alertDialog = builder.create()
alertDialog.show()
return alertDialog
}
private fun showDialog1(block: (AlertDialog.Builder) -> Unit): AlertDialog {
val builder = AlertDialog.Builder(this)
block.invoke(builder)
val alertDialog = builder.create()
alertDialog.show()
return alertDialog
}
handler.post()和handler.post{}區別
實戰1
//8.實戰1:創建jsonObject封裝
val jsonObject = JSONObject()
jsonObject.put("key1", "value1")
jsonObject.put("key2", "value2")
createJson(
"key1" to "value1",
"key2" to 1001,
"key2" to createJson(
"inner1" to ""
)
)
private fun <V> createJson(vararg pairs: Pair<String, V>): JSONObject =
JSONObject().apply {
for ((key, value) in pairs) {
put(key, value)
}
}
實戰2
//8.實戰2:Notification封裝
val builder = NotificationCompat.Builder(this, "")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("通知")
.setContentText("有新版本更新!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
NotificationManagerCompat.from(this).notify(1,builder.build())
自定義View時構造函數問題
class ChapterListView @JvmOverloads constructor(
val mContext: Context, attrs: AttributeSet? = null
) : LinearLayout(mContext, attrs) {}
Kotlin 重載個方法,還有兩幅面孔,省代碼的同時也帶來一個深坑 | Kotlin 原理
kotlin小技巧
- 函數內部定義函數,縮小方法作用域
- AbDialog 類似高階函數 lambda