Kotlin android-freestyle

    • 一 配置
    • 二 实践
      • step1 页面设计
      • step2 数据库设计

一、 配置

  • Project/build.gradle 配置
buildscript {
    ext {
        support_version = '25.3.0'
        gradle_version = '2.3.0'
        kotlin_version = '1.1.2-3'
        anko_version = '0.8.2'
    }
    repositories {
        jcenter()
        dependencies {
            classpath 'com.android.tools.build:gradle:2.3.0'
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
            classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
        }
    }
}
  • Model/build.gradle 配置
    • kotlin-stdlib 为基础的依赖包
    • anko-common 为简化 Android 任务开发,大写的扩展函数
    • anko-sqlite 本地数据库
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

dependencies {
    ...
    compile "com.android.support:appcompat-v7:$support_version"
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile "org.jetbrains.anko:anko-common:$anko_version"
    compile "org.jetbrains.anko:anko-sqlite:$anko_version"
}

android{
    sourceSets {
        // 提示:需手动创建 kotlin 目录
        main.java.srcDirs += 'src/main/kotlin'
    }
}

二、 实践

step1. 页面设计

  • activity_layout.xml 创建,跟往常一样

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/main_rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

android.support.constraint.ConstraintLayout>
  • item_main.xml 同样是没啥特别的

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/main_item_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

LinearLayout>
  • UserInfo.kt 用户信息-数据类
    • data 作为修饰符
    • Json 解析字段与参数名一致,也可 Serialised 实现序列化
data class UserInfo(val name: String, val age: Int)
  • MainRvAdapter.kt 适配器创建与列表项展示,有如下改变:
    • 数组取值统一采用 .[index] 形式,抛去以往的 get 函数
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.nuon.kj.MainRvAdapter.ViewHolder
import kotlinx.android.synthetic.main.item_main.view.*

class MainRvAdapter(val items: List, val itemClick: (UserInfo) -> Unit)
    : RecyclerView.Adapter() {

    override fun getItemCount(): Int {
        return items.size
    }

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

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_main, null)
        return ViewHolder(view, itemClick)
    }

    class ViewHolder(val view: View, val itemClick: (UserInfo) -> Unit)
        : RecyclerView.ViewHolder(view) {
        // val mNameTv: TextView = view.findViewById(R.id.main_item_tv) as TextView

        fun binData(info: UserInfo) {
            with(info) {
                // mNameTv.text = name

                // 这里通过 kotlin-android-extensions 提供的模板实现视图获取(id)
                view.main_item_tv.text = name
                view.main_item_tv.setTextColor(ContextCompat.getColor(view.context, R.color.colorAccent))
            }

            view.setOnClickListener {
                itemClick.invoke(info)
            }
        }
    }
}
  • MainActivity.kt 创建与视图声明,有如下改变:
    1. 数组定义使用 listOf 函数实现其赋值
    2. 对象定义使用 var/val 命名,类型转换 as
    3. setLayoutManager() 由 set 函数更新为 .layoutManager 表示
    4. 对象的实例化省去 new 字串的编辑
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.nuon.kj.db.UserInfo
import org.jetbrains.anko.startActivitylass MainActivity : AppCompatActivity() {

    var mMainRv: RecyclerView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initView()
    }

    fun initView() {
        val user1 = UserInfo("Joke", 22)
        val user2 = UserInfo("Ming", 26)
        val user3 = user1.copy(name = "Tome")// 对象赋值
        val userList = listOf(user1, user2, user3)

        val mMainRv = findViewById(R.id.main_rv) as RecyclerView
//        val mMainRv: RecyclerView = find(R.id.main_rv)// anko 简化实现
        mMainRv.layoutManager = LinearLayoutManager(this)
        mMainRv.adapter = MainRvAdapter(userList) {// 扩展函数引用
//            Toast.makeText(this@MainActivity, it.name, Toast.LENGTH_SHORT).show()

//            val intent = Intent(MainActivity@this, DetailActivity::class.java)
//            intent.putExtra("userName", it.name)
//            startActivity(intent)

            startActivity("userName" to it.name)// anko 实现
        }
    }
}

step2 数据库设计

  • UserTable.kt 创建表结构,用于存储账号信息
object UserTable {
    val TableName = "_user"
    val ID = "_id"
    val Pwd = "pwd"
    val UserName = "userName"
    val Age = "age"
    val Sex = "sex"
}
  • UserInfo.kt 创建表对象
data class UserInfo(val map: MutableMap<String, Any?>) {
    var _id: Long by map
    var loginId: String by map
    var pwd: String by map
    var userName: String by map
    var age: Int by map
    var sex: String by map

    constructor() : this(HashMap())

    constructor(id: Long, loginId: String, pwd: String, userName: String, age: Int, sex: String) : this(HashMap()){
        this._id = id
        this.loginId = loginId
        this.pwd = pwd
        this.userName = userName
        this.age = age
        this.sex = sex
    }
}

待更新…

Kotlin self-freestyle
Kotlin java-freestyle

你可能感兴趣的:(Kotlin)