導(dǎo)入
在AndroidStudio中安裝kotlin插件塌衰,AndroidStudio 3.0-pre 已經(jīng)自帶kotlin
project-build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.1.3'
ext.anko_version = '0.10.1'
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
jcenter()
maven { url "http://dl.bintray.com/kotlin/kotlin-dev" }
}
}
app-build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile "org.jetbrains.anko:anko-sdk25:$anko_version"
compile "org.jetbrains.anko:anko-sdk25-coroutines:$anko_version"
compile "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
}
利用Kotlin開發(fā)Android常見小記
1.去掉findViewById
通過build.gradle中加入apply plugin: 'kotlin-android-extensions' 來實現(xiàn)诉稍。
布局文件activity_main.xml中的一部分
<Button
android:id="@+id/btn_base_click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="基礎(chǔ)控件語法" />
Activity.kt 中使用
import kotlinx.android.synthetic.main.activity_main.*
//直接通過xml-id 進行使用
btn_base_click.setOnClickListener(this)
2.使用Anko-Layouts來寫布局?
like this
verticalLayout {
val name = editText()
button("Say Hello") {
onClick { toast("Hello, ${name.text}!") }
}
}
由于多年的xml 布局經(jīng)驗最疆,我還是直接用==xml 布局方便==杯巨,雖然xml 在parse資源過程中會帶來一些性能消耗,但是無關(guān)大雅肚菠。
3.Anko-Commons中如何實現(xiàn)activity之間跳轉(zhuǎn)
A->B
定義:
inline fun <reified T: Activity> Context.startActivity(vararg params: Pair<String, Any>)
Use-withData:
startActivity<YOUR_ACTIVITY>(DATA_KEY to DATA)
Use-noData:
startActivity<YOUR_ACTIVITY>()
A->B->A
定義
inline fun <reified T: Activity> Activity.startActivityForResult(requestCode: Int, vararg params: Pair<String, Any>)
Use-withData:
startActivityForResult<YOUR_ACTIVITY>(requestCode = 1,DATA_KEY to DATA)
Use-noData:
startActivityForResult<YOUR_ACTIVITY>(requestCode = 1)
4.如何創(chuàng)建單例
在kotlin直接用object 關(guān)鍵字創(chuàng)建舔箭,就是一個單例
object Single {
fun getData(): String {
return "this a single object"
}
}
5.如何創(chuàng)建java-bean data類
創(chuàng)建一個最簡單的data 類
data class JavaBean(var name: String, var sex: String) {
}
說到這里講一講構(gòu)造函數(shù),構(gòu)造函數(shù)分為主構(gòu)造函數(shù)和次構(gòu)造函數(shù)蚊逢。
主構(gòu)造函數(shù),如果需要對進行更改可以調(diào)用init方法
data class Data(var name){
init{
//進行一些初始化或者其他操作
}
}
次構(gòu)造函數(shù):层扶。如果類有一個主構(gòu)造函數(shù)(無論有無參數(shù)),每個次構(gòu)造函數(shù)需要直接或間接委托給主構(gòu)造函數(shù)烙荷,用this關(guān)鍵字
data class Data(var name){
init{
//進行一些初始化或者其他操作
}
constructor(name: String, age: Int) :this(name) {
}
}
}
6.如何定義靜態(tài)常量
在某個類中
class Constant{
companion object {
val DATA = "data"
}
}
Use : var data = Constant.DATA
7.Kotlin-stdlib自帶的高階函數(shù)
- apply
定義
/**
* Calls the specified function [block] with `this` value as its receiver and returns `this` value.
*/
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
使用
object.apply{
可以使用該object 任何方法镜会,返回該object
}
var applyTextView = TextView(this).apply {
text = "我是測試apply 方法, textview"
textColor = Color.BLUE
textSize = 16F
}
- with
定義
/**
* Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
使用
with(object){
可以使用該object任何方法终抽,返回block
}
var withTextView = TextView(this)
with(withTextView) {
text = "我是測試with 方法的 textview"
textColor = Color.BLUE
textSize = 18f
}
- let
定義
/**
* Calls the specified function [block] with `this` value as its argument and returns its result.
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)
使用
object.let{//將object 轉(zhuǎn)換成it對象戳表,然后通過it 對象進行其他操作}
withTextView.let {
it.text = "通過let 進行更改"
}
- run
定義
/**
* Calls the specified function [block] with `this` value as its receiver and returns its result.
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R = block()
使用object.run{之行一段代碼}
"我是測試run方法的 textview".run { toUpperCase() }
- to
該函數(shù)主要用于Pair類型的賦值,如map昼伴,set等
val map = mapOf("a" to 1,"b" to 2)
- lazy
延遲加載匾旭,只有當(dāng)使用的時候才進行加載
val lazyText by lazy {
TextView(this).apply {
text = "我是測試lazy 方法的 textview".run { toUpperCase() }
textColor = Color.BLUE
textSize = 18f
}
}
//when view.addView(lazyText) this textView will load
8.Anko-Commons 其他封裝的函數(shù)
- toast
Toasts.kt類中對toast提供了下面2類進行封裝
android.app.Fragment
android.content.Context
toast() //對應(yīng)LENGTH_SHORT
longToast() //對應(yīng)LENGTH_LONG
AndroidDialog.kt文件中做了很多擴張方法。
- alert 創(chuàng)建對話框
alert{
title = "真的可以這樣用嘛"
message = "好像真的可以啊"
okButton {
toast("確認(rèn)button")
}
cancelButton {
toast("取消button")
}
}.show()
- indeterminateProgressDialog 旋轉(zhuǎn)進度,默認(rèn)點擊其他view 消失
indeterminateProgressDialog(message = "正在加載", title = "我是title") {
}.show()
- progressDialog 百分比進度條
val pd = progressDialog(message = "正在加載", title = "我是title")
with(pd){
incrementProgressBy(20)
show()
}
- ContextUtilsKt.kt 中find 方法
其中
Activity圃郊,Dialog价涝,F(xiàn)ragment,View均擴展該方法
find<YourView>(R.id.xxx)
var btn = find<Button>(R.id.btn_list_click)
封裝庫中擴展函數(shù)千千萬,需要慢慢用持舆,慢慢看色瘩。
9.如何理解kotlin中的inline 內(nèi)聯(lián)函數(shù)
每一個函數(shù)都是一個對象,并且會捕獲一個閉包逸寓。
傳統(tǒng)函數(shù)調(diào)用順序
a()->b()->c()
a()執(zhí)行完成之后居兆,返回到內(nèi)存地址,然后執(zhí)行下一個函數(shù)指令竹伸,開始調(diào)用b(),當(dāng)b()執(zhí)行完成之后泥栖,回到內(nèi)存地址,然后開始執(zhí)行c()函數(shù)的指令,存在一個出棧壓棧的過程聊倔,在空間和時間上都有一定的消耗晦毙。
這種情況下生巡,內(nèi)聯(lián)函數(shù)的出現(xiàn)耙蔑,即增加了少許空間,但是減少了時間上的消耗孤荣。直接在函數(shù)體內(nèi)部執(zhí)行下一個函數(shù)體甸陌。
自定義一個內(nèi)聯(lián)函數(shù)
a.函數(shù)體沒有其他操作
inline fun testInline(block: () -> Unit) = block()
Use:
testInline{
println("this is block body")
}
b.函數(shù)體中有其他操作
inline fun testInline(times:Int,block:(Int)->Unit){
for (index in 0..times - 1) {
block(index)
}
}
Use: print : 0-9
testInline(10){
println(it)
}
注:如果內(nèi)聯(lián)函數(shù)有多個block 可以用noline 去指定那一個不內(nèi)聯(lián)。reified來具體化參數(shù)類型
10.如何使用擴展函數(shù)盐股,來擴展自己的Android-Utils
先來認(rèn)識什么是擴展函數(shù)
簡單點來說钱豁,就是真對已有的類,擴展一些新的方法疯汁,而不改變原類本身牲尺。
寫一個最簡單的擴展
fun Activity.sayHelloWorld() {
toast("Hello World")
}
Use:for every Activity
sayHelloWorld()
可選參數(shù)和默認(rèn)值
fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT){
Toast.makeText(this, message, duration)
}
Use:
toast("HelloWorld!!")
toast("HelloWorld!!", Toast.LENGTH_LONG)
reified具體化參數(shù),類傳遞
fun <reified : Activity> Activity.to() {
toast(this.toString())
}
Use:
to<YourActivity>()
11.Kotlin哪些讓人向往的高階操作函數(shù)
-
map
返回一個每一個元素根據(jù)給定的函數(shù)轉(zhuǎn)換所組成的List,將集合的每一個元素it進行傳遞下去幌蚊。
val datas = listOf(1,3,5,7,9)
datas.map{
it+2
}
//print: datas = [3,5,7,9,11]
- **filter** 過濾操作谤碳,過濾所有符合給定函數(shù)條件的元素。
val datas = listOf(1,3,5,7,9)
datas.filter{
it>5
}
//print:datas = [7,9]
- **sort** 返回一個自然排序后的list溢豆。
- **sortBy**返回一個根據(jù)指定函數(shù)排序后的list蜒简。
- **sortDescending** 降序
- **forEach**遍歷所有元素,并執(zhí)行給定的操作漩仙。
##### [Kotlin學(xué)習(xí)資料](https://www.gitbook.com/book/wangjiegulu/kotlin-for-android-developers-zh/details)