上一篇咱們作到了從網絡獲取數據,並寫好了實體類.接着咱們須要建立domain層,這一層爲app執行任務.java
構建domain層
首先須要建立command:android
public interface Command<T> {
fun execute() : T
}
複製代碼
建立DataMapper:git
class ForecastDataMapper {
fun convertFromDataModel(forecast: ForecastResult): ForecastList {
return ForecastList(forecast.city.name, forecast.city.country, convertForecastListToDomain(forecast.list))
}
fun convertForecastListToDomain(list: List<ForecastResult.ForeCast>) : List<ModelForecast> {
return list.map { convertForecastItemToDomain(it) }
}
private fun convertForecastItemToDomain(forecast: ForecastResult.ForeCast): ModelForecast {
return ModelForecast(convertDate(forecast.dt),
forecast.weather[0].description, forecast.temp.max.toInt(),
forecast.temp.min.toInt())}
private fun convertDate(date: Long): String {
val df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault())
return df.format(date * 1000)
}
data class ForecastList(val city: String, val country: String,val dailyForecast:List<Forecast>)
data class Forecast(val date: String, val description: String, val high: Int,val low: Int)
}
複製代碼
Tips:
list.map:循環這個集合並返回一個轉換後的新list.github
準備就緒:算法
class RequestForecastCommand(val zipCode : String) : Command<ForecastDataMapper.ForecastList> {
override fun execute(): ForecastDataMapper.ForecastList {
return ForecastDataMapper().convertFromDataModel(Request(zipCode).execute())
}
}
複製代碼
綁定數據,刷新ui:編程
doAsync {
val result = RequestForecastCommand("94043").execute()
uiThread {
recycler.adapter = ForecastListAdapter(result)
}
}
複製代碼
同時須要修改adapter數據類型:安全
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
with(items.dailyForecast[position]){
holder.textView.text = "$date - $description - $high/$low"
}
}
override fun getItemCount(): Int {
return items.dailyForecast.size
}
複製代碼
Tips:
關於with函數:它接收一個對象和一個擴展函數做爲它的參數,而後使這個對象擴展這個函數。這表示全部咱們在括號中編寫的代碼都是做爲對象(第一個參數)的一個擴展函數,咱們能夠就像做爲this同樣使用全部它的public方法和屬性。當咱們針對同一個對象作不少操做的時候這個很是有利於簡化代碼。bash
運行一下項目,能夠看到效果以下圖:網絡
添加item點擊事件
先看下效果圖:app
咱們把對應的item佈局修改成圖上的樣子後,修改ForecastDataMapper:
private fun convertForecastItemToDomain(forecast: ForecastResult.ForeCast): ModelForecast {
return ModelForecast(convertDate(forecast.dt),
forecast.weather[0].description,
forecast.temp.max.toInt(),
forecast.temp.min.toInt(),
generateIconUrl(forecast.weather[0].icon))}
private fun convertDate(date: Long): String {
val df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault())
return df.format(date * 1000)
}
private fun generateIconUrl(iconCode : String) : String{
return "http://openweathermap.org/img/w/$iconCode.png"
}
data class Forecast(val date: String, val description: String, val high: Int,val low: Int,val iconUrl : String)
複製代碼
修改adapter:
class ForecastListAdapter(val items : ForecastDataMapper.ForecastList,
val itemCLick : onItemClickListenr) :
RecyclerView.Adapter<ForecastListAdapter.ViewHolder>(){
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
with(items.dailyForecast[position]){
holder.bindForecast(items.dailyForecast[position])
}
}
override fun getItemCount(): Int {
return items.dailyForecast.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_forecast,parent,false)
return ViewHolder(view,itemCLick)
}
class ViewHolder(view : View , val onItemClick : onItemClickListenr) : RecyclerView.ViewHolder(view){
private val iconView : ImageView
private val dateView : TextView
private val descriptionView : TextView
private val maxTemperatureView : TextView
private val minTemperatureView : TextView
init {
iconView = view.find(R.id.icon)
dateView = view.find(R.id.date)
descriptionView = view.find(R.id.description)
maxTemperatureView = view.find(R.id.maxTemperature)
minTemperatureView = view.find(R.id.minTemperature)
}
fun bindForecast(forecast : ForecastDataMapper.Forecast ){
with(forecast){
Glide.with(itemView.context).load(iconUrl).into(iconView)
dateView.text = date
descriptionView.text = description
maxTemperatureView.text = high.toString()
minTemperatureView.text = low.toString()
itemView.setOnClickListener(){
onItemClick(forecast)
}
}
}
}
public interface onItemClickListenr{
operator fun invoke(forecast : ForecastDataMapper.Forecast)
}
}
複製代碼
以後綁定數據:
doAsync {
val execute = RequestForecastCommand("94043").execute()
uiThread {
recycler.adapter = ForecastListAdapter(execute, object :ForecastListAdapter.onItemClickListenr{
override fun invoke(forecast: ForecastDataMapper.Forecast) {
toast("點擊了item")
}
})
}
}
複製代碼
有時候咱們可能會遇到一個異常:
[Kotlin]kotlin.NotImplementedError: An operation is not implemented: not implemented
緣由 : Android裏面加個TODO並不會影響程序運行,但是在Kotlin裏面就不同啦,若是你在某個函數的第一行添加TODO的話,那麼很抱歉,它不會跳過,而後運行下一行代碼
解決方案: 咱們只須要把TODO("not implemented") 這句話去掉就能夠啦!
簡化setOnCLickListener kotlin版的點擊事件:
view.setOnClickListener(object : View.OnClickListener{
override fun onClick(v: View?) {
toast("click")
}
})
複製代碼
或者
view.setOnClickListener {
toast("click")
}
複製代碼
Kotlin Android Extensions
這個插件自動建立了不少的屬性來讓咱們直接訪問XML中的view。這種方式不須要你在開始使用以前明確地從佈局中去找到這些views。這些屬性的名字就是來自對應view的id,因此咱們取id的時候要十分當心.
dependencies {
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
}
複製代碼
使用的時候咱們只須要作一件事:在activity或fragment中手動import以kotlinx.android.synthetic開頭的語句 + 要綁定的佈局名稱:
import kotlinx.android.synthetic.main.activity_main.*
複製代碼
而後刪掉你的find(findviewbyid)吧,直接使用xml中的佈局id來作操做 簡化你在activity和adapter中的代碼吧!
Tips: 若是佈局中包含includ標籤的佈局,還須要在activity中再導入include的佈局才能使用
委託模式
所謂委託模式 ,就是爲其餘對象提供一種代理以控制對這個對象的訪問,在 Java 開發過程當中,是繼承模式以外的很好的解決問題的方案。
interface Base {
fun print()
}
class A(val a: Int) : Base {
override fun print() {
Log.d("wxl", "a=" + a)
}
}
class B (val base: Base):Base by base
複製代碼
調用:
val a = A(1)
Log.d("wxl", "a=" + B(a).print())
複製代碼
集合和函數操做符
關於函數式編程:
很不錯的一點是咱們不用去解釋咱們怎麼去作,而是直接說我想作什麼。好比,若是我想去過濾一個list,不用去建立一個list,遍歷這個list的每一項,而後若是知足必定的條件則放到一個新的集合中,而是直接食用filer函數並指明我想用的過濾器。用這種方式,咱們能夠節省大量的代碼。
Kotlin提供的一些本地接口:
kotlin中的null安全
指定一個變量是可null是經過在類型的最後增長一個問號:
val a: Int? = null
//若是你沒有進行檢查,是不能編譯經過的
a.toString()
//必須進行判斷
if(a!=null){
a.toString()
}
複製代碼
控制流-if表達式
用法和 Java 同樣,Kotlin 中一切都是表達式,一切都返回一個值。
val l = 4
val m = 5
// 做爲表達式(替換java三元操做符)
val n = if (l > m) l else m
複製代碼
When 表達式 When 取代 Java switch 操做符。
val o = 3
when (o) {
1 -> print("o == 1")
2 -> print("o == 2")
else -> {
print("o == 3")
}
}
複製代碼
還能夠檢測參數類型:
when(view) {
is TextView -> view.setText("I'm a TextView")
is EditText -> toast("EditText value: ${view.getText()}")
is ViewGroup -> toast("Number of children: ${view.getChildCount()} ")
else ->
view.visibility = View.GONE}
複製代碼
For 循環
for (item in collection) {
print(item)
}
複製代碼
須要使用index:
for (i in list.indices){
print(list[i])
}
複製代碼
泛型
泛型編程包括,在不指定代碼中使用到的確切類型的狀況下來編寫算法。用這種方式,咱們能夠建立函數或者類型,惟一的區別只是它們使用的類型不一樣,提升代碼的可重用性。
建立一個指定泛型類:
classTypedClass<T>(parameter: T) {
val value: T = parameter
}
複製代碼
這個類如今可使用任何的類型初始化,而且參數也會使用定義的類型(kotlin編譯器能夠判斷類型,因此尖括號能夠省略):
val t1 = TypedClass<String>("Hello World!")
val t2 = TypedClass<Int>(25)
複製代碼
一首好音樂:Fall Back-Yonas
音樂人: 約納斯住宿加早餐旅館
首張收錄專輯: The Proven Theory
發行時間: 2011 年
流派: 嘻哈/饒舌
項目已經更新到github: github.com/saurylip/Ko…