第十四章 使用Kotlin開發Android程序
Kotlin for android
https://github.com/EasyKotlin/Kotlin-for-Android-Developers
展示一個實現登錄注冊的demo
下面就我們就開始一個入門級別的demo吧,現在谷歌已經推出了android studio3.0已經支持了Kotlin這門語言,下載地址:https://developer.android.google.cn/studio/preview/index.html ,只需要在這里新建一個工程,然后在是否要加入kotlin的選項上面勾一下就可以了。
下面看一下登錄注冊的代碼:
class MainActivity : AppCompatActivity() {
var userName: EditText? = null
var userPwd: EditText? = null
var register: Button? = null
var login: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
userName = findViewById(R.id.user_name) as EditText
userPwd = findViewById(R.id.user_pwd) as EditText
register = findViewById(R.id.register) as Button
login = findViewById(R.id.login) as Button
login!!.setOnClickListener {
if (userName!!.text.toString() == "123456" && userPwd!!.text.toString() == "abc") {
Toast.makeText(this, "login succeed1", Toast.LENGTH_SHORT).show()
val intent = Intent(this,HomeActivity::class.java)
startActivity(intent)
}
}
register!!.setOnClickListener {
Toast.makeText(this, "the function has not open ...", Toast.LENGTH_SHORT).show()
}
}
}
當然實現的代碼就非常簡單啦,只是可能我們在剛開始接觸這門語言的時候有一些的不理解。大家可以看一下上面的代碼,要是有什么不理解的地方歡迎issue。
源碼地址:https://github.com/linsir6/Kotlin
https://github.com/EasyKotlin/Bandhook-Kotlin
Kotlin生態庫
項目模式
Kotlin
讓你的代碼量大大減少,函數式編程讓你爽到飛上天!如果你想學習Kotlin,本項目應該會給你不少幫助。
MVP
通過契約類Contract管理View Model Presenter接口。
- Model -- 主要處理業務,用于數據的獲取(如網絡、本地緩存)。
- View -- 用于把數據展示,并且提供交互。
- Presenter -- View和Model交互的橋梁,二者通過Presenter建立聯系。
主要流程如下: 用戶與View交互,View得知用戶需要加載數據,告知Presenter,Presenter則告知Model,Model拿到數據反交于Prsenter,Presenter將數據交給View進行展示。
Dagger2
項目中,主要進行presenter、model、retrofit Api等類的注入操作。
ApiComponent
主Component、用于注入AppComponent、便于提供子Component依賴。
依賴于:
1.ApiModule(提供okhttpClient、Retrofit、Api等)
2.AppModule(提供context對象(okhttp攔截器所需))
FuckGoodsComponent
父Component為ApiComponent 用于注入FuckGoodsPresenter
依賴于: FuckGoodsModule(提供FuckGoodsView)
RandomComponent
父Component為ApiComponent 用于注入RandomPresenter
依賴于 : RandomModule(提供RandomView)
Rxjava + Retrofit + okhttp3
主要用于網絡訪問。
DeepLinkDispatch
基于路由進行頁面轉發。
GankClientUri 定義一些路由規則、URI等
GankRouter 統一由此進行路由操作
GSON
用于json的解析操作。
Glide
用于圖片的加載。
ByeBurGer
用于導航欄以及懸浮按鈕滑動隱藏。
參考資料
1.http://git.bookislife.com/post/2016/dev-android-using-scala/
2.https://github.com/saturday06/gradle-android-scala-plugin
3.https://github.com/pocorall/scaloid
Kotlin 開發者社區
國內第一Kotlin 開發者社區公眾號,主要分享、交流 Kotlin 編程語言、Spring Boot、Android、React.js/Node.js、函數式編程、編程思想等相關主題。