Kotlin實踐記錄

Kotlin中網絡請求和Json解析:

Request(url).run()爲Kotlin中的網絡請求方式,Json解析是本身封裝類的操做。
Json.get().toObject(Request(url).run(), GankNewsList::class.java).results 是將返回結果轉換爲具體的bean對象
DataLoader.kt 
import com.soyoungboy.kotlinapp.util.json.Json

/**
 * Created by soyoungboy on 2018/1/29.
 */
class DataLoader {

    fun getGankNewsList(date: String): List<GankNews> {
        val url = Request.BASE_URL + date
        return Json.get().toObject(Request(url).run(), GankNewsList::class.java).results
    }

    fun getGankPictureList(date: String): ArrayList<GankPicture> {
        val url = Request.BASE_URL + date
        return Json.get().toObject(Request(url).run(), GankPictureList::class.java).results
    }
}
Json.kt
package com.soyoungboy.kotlinapp.util.json

abstract class Json internal constructor() {


    abstract fun toJson(src: Any): String

    abstract fun <T> toObject(json: String, claxx: Class<T>): T

    abstract fun <T> toObject(bytes: ByteArray, claxx: Class<T>): T

    abstract fun <T> toList(json: String, claxx: Class<T>): List<T>?

    companion object {
        private var json: Json? = null


        fun get(): Json {
            if (json == null) {
                json = GsonImpl()
            }
            return json as Json
        }
    }
}

具體的json解析封裝:java

package com.soyoungboy.kotlinapp.util.json

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.util.*

/**
 * Created by soyoungboy on 2017/12/25.
 */

class GsonImpl : Json() {
    private val gson = Gson()


    override fun toJson(src: Any): String {
        return gson.toJson(src)
    }


    override fun <T> toObject(json: String, claxx: Class<T>): T {
        return gson.fromJson(json, claxx)
    }


    override fun <T> toObject(bytes: ByteArray, claxx: Class<T>): T {
        return gson.fromJson(String(bytes), claxx)
    }


    override fun <T> toList(json: String, claxx: Class<T>): List<T>? {
        val type = object : TypeToken<ArrayList<T>>() {

        }.type
        return gson.fromJson<List<T>>(json, type)
    }

}

bean對象:android

GankNewsList.ktgit

package com.soyoungboy.kotlinapp.bean

/**
 * Created by soyoungboy on 2018/1/29.
 */
class GankNewsList(val error: Boolean, val results: List<GankNews>)

GankNews.ktgithub

package com.soyoungboy.kotlinapp.bean

/**
 * Created by soyoungboy on 2018/1/29.
 */
data class GankNews(val _id: String,
                    val createdAt: String,
                    val desc: String,
                    val publishedAt: String,
                    val type: String,
                    val url: String,
                    val used: Boolean,
                    val who: String)

Kotlin異步線程和主線程之間的切換

async {}爲異步代碼塊
uiThread {}爲主線程代碼塊
private fun getGanksNewsList() = async {
        val news = DataLoader().getGankNewsList("data/all/20/2")
        uiThread {
            forecast_list.adapter = GankNewsAdapter(news) {
                val intent = Intent()
                intent.setClass(this@GankNewsListActivity, WebActivity::class.java)
                intent.putExtra("url", it.url)
                startActivity(intent)
            }
        }

    }

kotlin跳轉和數據傳遞:

intent跳轉並攜帶數據:json

val intent = Intent()
intent.setClass(this@GankNewsListActivity, WebActivity::class.java)
intent.putExtra("url", it.url)
startActivity(intent)

接收數據:緩存

intent.getStringExtra("url")爲接收數據操做
override fun getUrl(): String {
        return intent.getStringExtra("url")
    }

kotlin圖片加載:

因爲Kotlin和Java代碼之間能夠相互操做,因此Kotlin能夠調用Android相關的圖片加載庫,這裏用Glide舉例子:網絡

引入Glideapp

compile 'com.github.bumptech.glide:glide:4.1.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.1.1'
compile 'com.github.bumptech.glide:okhttp3-integration:4.0.0'

對Glide的封裝異步

代碼見:async

https://github.com/soyoungboy/KotlinApp/tree/master/app/src/main/java/com/soyoungboy/kotlinapp/util/glide

調用如上ImageUtils進行圖片加載緩存

class ViewHolder(val view: View, val itemClickListener: (GankPicture) -> Unit) : RecyclerView.ViewHolder(view) {
        fun bind(pictures: GankPicture) {
            val meizi = view.meizi as ImageView
            ImageUtils.loadImage(pictures.url,meizi)
            view.title.text = pictures.desc
            view.setOnClickListener {
                itemClickListener(pictures)
                view.context.longToast(pictures.url)
            }
        }
    }

kotlin之RecyclerView對應的Adapter

val items: List<GankPicture> 爲要傳進來進行展現的數據
view.setOnClickListener {
                itemClickListener(pictures)
                view.context.longToast(pictures.url)
            }
爲點擊事件

package com.soyoungboy.kotlinapp.adapter

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.soyoungboy.kotlinapp.R
import com.soyoungboy.kotlinapp.bean.GankPicture
import com.soyoungboy.kotlinapp.util.glide.ImageUtils
import kotlinx.android.synthetic.main.item_meizi.view.*
import org.jetbrains.anko.longToast

/**
 * Created by soyoungboy on 2018/1/29.
 */
class GankPictureAdapter(val items: List<GankPicture>, val itemClickListener: (GankPicture) -> Unit) : RecyclerView.Adapter<GankPictureAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_meizi, parent, false)
        return ViewHolder(view, itemClickListener)
    }

    override fun getItemCount(): Int = items.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(items[position])
    }

    class ViewHolder(val view: View, val itemClickListener: (GankPicture) -> Unit) : RecyclerView.ViewHolder(view) {
        fun bind(pictures: GankPicture) {
            val meizi = view.meizi as ImageView
            ImageUtils.loadImage(pictures.url,meizi)
            view.title.text = pictures.desc
            view.setOnClickListener {
                itemClickListener(pictures)
                view.context.longToast(pictures.url)
            }
        }
    }
}

實踐的代碼見個人github:https://github.com/soyoungboy/KotlinApp,裏面是我學習Kotlin的一些小練習

相關文章
相關標籤/搜索