Kotlin: Android Development Tips
Kotlin is the first language for Android development, but most of the people doing Android still use java. The trend of Android switching to Kotlin is inevitable. The next-door department of the company has already used Kotlin for development. We will also focus on Kotlin in new projects in the future. Regarding the knowledge of Kotlin, the blogger only read the tutorials on the official website in the second half of last year, also read "Kotlin for Android Developers", and wrote a practice project, but more than half a year has passed, and the knowledge learned before It's not easy to pick it up again, so I summarized some common skills of Kotlin in Android development.
Basic Kotlin skills
singleton
Kotlin is a very simple language, and so are singletons. Here are two commonly used singleton formats: The first one: implement singletons through companion objects + delegates
class App : MultiDexApplication() {
companion object {
var INSTANCE: APP by Delegates.notNull()
}
override fun onCreate() {
INSTANCE = this
}
}
As in the above code, declare the variable in the companion object, and use the netNull delegate to avoid the null exception check in Kotlin, and then assign the value in onCreate
The second type: Kotlin keyword object
object CommonParam {
var TAG = ""
}
Is Kotlin's writing method very simple and rude?
Kotlin delegation
Kotlin supports delegation, including class delegation, standard delegation, and custom delegation. Students can read my previous blog: Kotlin commissioned
run、with、apply、alse、let、takeIf、repeat
|
field
|
effect
|
| — | — |
|
T.run(block: () -> R)
|
Run the function and return the result of the function
|
|
T.with(receiver: T, block: T.() -> R)
|
The receiver is used as this of the block function, and returns the function running result
|
|
T.apply(block: T.() -> Unit)
|
Run the function, returning the caller itself
|
|
T.also(block: (T) -> Unit)
|
The caller acts as the function it, executes the function and returns the caller itself
|
|
T.let(block: (T) -> R)
|
The caller is the this of the block function, and returns the function running result
|
|
T.tabkeIf(predicate: (T) -> Boolean)
|
If the caller satisfies the condition of the function, it returns itself, otherwise it returns null
|
|
T.takeUnless(predicate: (T) -> Boolean)
|
The opposite of tabkeIf
|
|
repeat(times: Int, action: (Int) -> Unit)
|
Traverse times from 0 and run action
|
extension function
Kotlin can extend the properties and methods of a class without inheritance or using the Decorator pattern. Extension is a static behavior that does not have any impact on the extended class code itself. Here are a few commonly used extension functions:
/**
* Map<K, V?>类型转换为Array<out Pair<K, V>>类型
*/
fun <K, V : Any> Map<K, V?>.toVarargArray(): Array<out Pair<K, V>> =
map({ Pair(it.key, it.value!!) }).toTypedArray()
/**
* ImageView加载网络图片
*/
fun ImageView.loadImage(url: String) {
CommonModule.picasso.load(url).into(this)
}
/**
* anko.db框架中,数据库查询解析
*/
fun <T : Any> SelectQueryBuilder.parseList(parser: (Map<String, Any?>) -> T): List<T> =
parseList(object : MapRowParser<T> {
override fun parseRow(columns: Map<String, Any?>): T = parser(columns)
})
fun <T : Any> SelectQueryBuilder.parseOpt(parser: (Map<String, Any?>) -> T): T? =
parseOpt(object : MapRowParser<T> {
override fun parseRow(columns: Map<String, Any?>): T = parser(columns)
})
Anko framework
Anko Commons
Anko Intent helpers:
startActivity(intentFor<SomeOtherActivity>("id" to 5).singleTop())
Anko Dialogs
toast("Hi there!") // Toast
snackbar(view, "Hi there!") // snacbar
alert("Hi, I'm Roy", "Have you tried turning it off and on again?") { // alert
yesButton { toast("Oh…") }
noButton {}
}.show()
selector("Where are you from?", countries, { dialogInterface, i -> // selector
toast("So you're living in ${countries[i]}, right?")
})
AnkoLogger
class SomeActivity : Activity(), AnkoLogger {
private fun someMethod() {
info("London is the capital of Great Britain")
debug(5) // .toString() method will be executed
warn(null) // "null" will be printed
}
}
Colors
0xff0000.opaque // 转变为不透明的颜色
0x99.gray.opaque // 转变为不透明的灰色
0xabcdef.withAlpha(0xCF) == 0xCFabcdef // 设置透明度
Dimensions
dip(dipValue) // dip转换为px
sp(spValue) // sp转换为px
px2dip/px2sp // px转换为dip或者sp
Anko Layouts
For Anko Layouts, it is equivalent to writing xml in the code in the form of DSL. It seems very convenient, but the poster is still used to the xml method. Anko Layouts is used less. Friends who want to use it can learn by themselves on Baidu. .
Anko SQLite
Anko provides a very convenient sql interface
class MyDatabaseOpenHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "MyDatabase", null, 1) {
companion object {
private var instance: MyDatabaseOpenHelper? = null
@Synchronized
fun getInstance(ctx: Context): MyDatabaseOpenHelper {
if (instance == null) {
instance = MyDatabaseOpenHelper(ctx.getApplicationContext())
}
return instance!!
}
}
override fun onCreate(db: SQLiteDatabase) {
// Here you create tables
db.createTable("Customer", true,
"id" to INTEGER + PRIMARY_KEY + UNIQUE,
"name" to TEXT,
"photo" to BLOB)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// Here you can upgrade tables, as usual
db.dropTable("User", true)
}
}
// Access property for Context
val Context.database: MyDatabaseOpenHelper
get() = MyDatabaseOpenHelper.getInstance(getApplicationContext())
Then, where you need to use data, just perform additions, deletions, modifications, and queries
database.use {
// `this` is a SQLiteDatabase instance
}
More Kotlin learning materials can be scanned for free!
"Advanced Kotlin Strengthening Practice" Chapter 1 Kotlin Introductory Tutorial Kotlin Overview Kotlin Comparison with Java Skillful Use of Android Studio Understanding Kotlin Basic Types Entering Kotlin Arrays Entering Kotlin Collections Complete Code Basic GrammarChapter 2 Kotlin Practical Guide to Avoiding Pitfalls
●Method input parameters are constants and cannot be modified
●No Companion, INSTANCE?
●Java overloading, how to make a clever transition in Kotlin?
●Kotlin’s empty-judgment posture
●Kotlin overwrites the method in the Java parent class
●Kotlin becomes “ruthless”, even TODO is not spared!
●Pits in is and as`
●Comprehension of Property in Kotlin
●also keyword
●takeIf keyword
●Singleton pattern writing
Chapter 3 Project Combat "Kotlin Jetpack Combat"
●Start from a Demo that worships the Great God
●What is the experience of writing Gradle scripts in Kotlin?
●The Triple Realm of Kotlin Programming
●Kotlin Higher-Order Functions
●Kotlin Generics ● Kotlin
Extensions ● Kotlin Delegation
The first chapter of "The Most Detailed Android Version of Kotlin Coroutine Advanced Combat in History"
Basic Introduction of Kotlin Coroutine
What is Coroutine
What is Job, Deferred, Coroutine Scope
Basic usage of Kotlin Coroutine
Chapter 2 Preliminary Explanation of Key Knowledge Points of Kotlin Coroutine
● Coroutine Scheduler
● Coroutine Context
● Coroutine Start Mode
● Coroutine Scope
● Suspend Function
Chapter 3 Exception Handling of Kotlin Coroutine
●Generation Process of Coroutine Exception
●Exception Handling of Coroutine
Chapter 4 The basic application of kotlin coroutines in Android
. Android uses kotlin coroutines
. Uses coroutines in Activity and Framgent
. Uses coroutines in ViewModel
. Uses coroutines in other environments.