1. 程式人生 > >極簡Kotlin-For-Android(二)

極簡Kotlin-For-Android(二)

上一篇我們做到了從網路獲取資料,並寫好了實體類.接著我們需要建立domain層,這一層為app執行任務.

構建domain層
首先需要建立command:

public interface Command<T> {
    fun execute() : T
}
複製程式碼

建立DataMapper:

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.

準備就緒:

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方法和屬性。當我們針對同一個物件做很多操作的時候這個非常有利於簡化程式碼。

執行一下專案,可以看到效果如下圖:

新增item點選事件 先看下效果圖:

我們把對應的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提供的一些本地介面:

  • Iterable:父類。所有我們可以遍歷一系列的都是實現這個介面.
  • MutableIterable:一個支援遍歷的同時可以執行刪除的Iterables.
  • Collection:這個類相是一個範性集合。我們通過函式訪問可以返回集合的size、是否為空、是否包含一個或者一些item。這個集合的所有方法提供查詢,因為connections是不可修改的.
  • MutableCollection:一個支援增加和刪除item的Collection。它提供了額外的函式,比如add、remove、clear等等.
  • List:可能是最流行的集合型別。它是一個範性有序的集合。因為它的有序,我們可以使用get函式通過position來訪問.
  • 。MutableList:一個支援增加和刪除item的List.
  • Set:一個無序並不支援重複item的集合.
  • MutableSet:一個支援增加和刪除item的Se.。
  • Map:一個key-value對的collection。key在map中是唯一的,也就是說不能有兩對key是一樣的鍵值對存在於一個map中.
  • MutableMap:一個支援增加和刪除item的map.

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)
複製程式碼