Android 快速入门笔记(整理中)

Android Studio X11 远程开发

TODO

解决中文显示为方块字体/乱码

sudo apt install ttf-wqy-microhei
fc-cache -f -v

Kotlin 语法

警告
此处内容为快速入门参考,可能有不严谨/不准确之处
如果你有JavaScript和Java基础,以及异步、协程、线程的概念,此处应该可以快速通关

声明/定义

Java static 替代

// MyKtClass.kt
class MyKtClass {
    companion object {
        val foo = "hello"
        ... //代替 java static
    }
}

// 从 Kotlin 调用
val foo = MyKtClass.foo

// 从 Java 调用
var foo = MyKtClass.Companion.getFoo();

var 与 val

var 可变,与 java 一致

val 不可变,等同于 finnal

不需要new

// Java
new Exception("foo")

// Kotlin
Exception("bar")

Coroutine 协程

用法类似 js 的 Promise

suspend fun() { } 等同于 js 的 async function() { }

Continuation<T> 等同于 js 的 Promise<T>

suspend fun helloKt() : String = suspendCoroutine<String> { cont: Continuation<String> ->
    cont.resume("hello world")
}

// 简化 平时这么写
suspend fun helloKt() = suspendCoroutine { cont ->
    cont.resume("hello world")
}

// 异步运行
launch {
    val str = helloKt()
    println(str)
}

// 阻塞运行
runBlocking {
    val str = helloKt()
    println(str)
}

// 阻塞运行 也可以
val str = runBlocking {
    helloKt()
}
println(str)

// TODO join async

返回异常

suspend fun helloKt(foo: Boolean) = suspendCoroutine { cont ->
    if (foo) {
        cont.resumeWithException(Exception("bar"))
    }
    cont.resume("hello world")
}

空值处理

// 可空变量
var foo : String? = null
// 安全调用
println(foo?.length)
// 非空断言
println(foo!!.length)
// Elvis操作符
println(foo?.length ?? 0)
暂无评论

发送评论 编辑评论


|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇