Android Kotiln讲解

作者:XINHAO_HAN

第一版更新:2017.10

Kotiln需要下载Android Studio3.0或者Kotiln插件,百度喲~

那就开始直接入正题吧

Android Kotiln自定义变量,和普通JAVA有什么不同
//先从简单到难吧~~~
来,看->LOOK
基本数据:

//JAVA
String string;
int age;
//Kotiln
string:String;
age:Integer;
var 表示变量,可赋值多次
val 表示常量,只能赋值一次

//如果定义的String赋值初始化值为null,必须得编译器知道
//比如
//需要加"?"表示该项可以为空
var string:String? = null

基本数组

Array
Array
Array
//初始化String
 var string1: Array = Array(10, { i -> (i * i).toString() })
//初始化Byte
 var ss: Array = Array(10, { s -> (s * s).toByte() })
//初始化Int
var yy: Array = Array(10, { x -> (x * x) })

what?这都是啥?看不懂啊!!!,先别急
我这样给你看

 var string1: Array = Array(4, { i -> (i * i).toString() })
//拆分

//var 你定义的名称:Array = Array(数组的大小,{一个变量} ->(变量*变量).to该数组的T)

//i会一直++
//初始值 0,1,4,9,16
//i先为0    { i -> (0 * 0).toString() } = "0"
//i为1  { i -> (1 * 1).toString() } = "1"
//i为2  { i -> (2 * 2).toString() } = "4"
//i 为3  { i -> (3 * 3).toString() } = "9"
//i 为4  { i -> (4 * 4).toString() } = "16"
看懂了吧,为什么要是"1","4","9","16",那是因为这些都是字符串加了个引号嘛

你说NO,我就要像这种初始化的,我想手动初始化该怎么办
//JAVA
private int[] arr = {1,2,3,4,5,6,7,8,9,0};

//Kotiln,有点不一样,哈哈,就是有点不一样
//Kotlin 也有无装箱开销的专门的类来表示原生类型数组: ByteArray、 ShortArray、IntArray 等等。这些类和 Array 并没有继承关系,但是 它们有同样的方法属性集。它们也都有相应的工厂方法:
var yy: IntArray = intArrayOf(10,1,2,3,4,5)

大概还有很多小数据,你还是看看官方的文档,这块只简单给你说一下怎么用,能让你快速上手

方法


//方法
 fun Palystat() {
  }
//重写父类方法,使用override 关键字
 override fun palystat() {

    }
//添加参数,注意Kotlin的参数都是val常量,不可更改!
 fun palystat(string:String) {
  }
//有返回值
fun palystat(string:String):Int/*返回值的类型*/{
}
//方法不可重写
final override fun Palystat(order: String, price: String, title: String){


    }


注意Kotlin的方法参数都是val常量,不可更改!



//Kotiln
class A:B{
}
//构造(第一种,无参)
class A:B{
    constructor(){
    }
}




//构造(第一种有参)

class A:B{
    constructor(){
    }
    constructor(string:String){

    }
}
//构造(第二种无参)
class A():B{
   
}
//构造(第二种有参)
class A(int:Int/*参数类型*/):B{
   
}

//调用父类构造
class A:B{
  constructor() : super()
}


//静态类,object在Kotlin中代表静态类
object A{
}

//调用父类
 constructor(context: Context?) : super(context) {
//表示Context可以为空
        initData()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        initData()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initData()
    }

//开始NEW一些东西

//NEW一个ArrayList
    var arr: ArrayList = ArrayList()
//new一个类,这样,千万不要写个new

//错误
  var class:类名 = new 类名()
//正确
    var class:类名 = 类名()

//使用if for语句

var int:Int = 一个随机数;

  if(int in 0..9){
//判断是否在0与9之间相当于JAVA的 int <9 && int >0
            
   }


val str = "Hello Kotlin !"  
var array = arrayOf("3","d","x","gfd","w"," ","k","5","1","","h","4")  
  
for (i in array) print(i) // 数组遍历                        结果:3dxgfdw k51h4  
println()  
for (i in array.reversed()) print(i) // 倒序                 结果:4h15k wgfdxd3  
println()  
for (i in 0..array.size-1) print(i) // .. 范围               结果:01234567891011  
println()  
for (i in 2..2) print(i)        //  2与2之间                         结果:2  
println()  
for (i in array.size downTo 3) print(i)     //               结果:1211109876543  
println()  
for (i in array.size - 1 downTo 0 step 5) print(array[i]) // 结果:4kd  
println()  
for (i in str) print(i) // 字符串遍历                        结果:Hello Kotlin !  
println()  
for (i in 0..str.lastIndex) print(i)                 //      结果:012345678910111213  
println()  
for (i in 0..str.length-1) print(i)                   //     结果:012345678910111213  
println() 



举例子:
  for(i in 0..arr.size - 1){ //0与arr.size之间

      Log.e("数据",arr.get(i))

     }

定义别名

//比如你就非要object作为变量名称使用
//如下
var object:Int=0
//这样肯定是不行的
需要加"`"符号
var `object`:Int = 0//就OK了

//强制转换

//A ->a
//B ->b
//现在有两个不同的类别需要强制装换
var b = a as b //关键字 as,将a类强制装换为b类 

//使用get,set方法赋值

  private val view1: View?
        get() {
            val view = UIUtils.getView(R.layout.view_line_kd)
            return view
        }

//变量
private var int: Int = 0
        get() {
            int = 0
            return  int
        }
//set

  private var int: Int = 0
        set(v) {
            int = v
            
        }

//相当于JAVA当中的get set方法,CLASS当中的Bean

创建闭包

    data class Dean(var string: String, var a: Int)
    //相当于JAVABean
      class Dean{
              private String string;
              private int a;
                ....
      }
 data class Dean(var string: String, var a: Int  /*...更多类型*/)

一下是我做的一个流逝布局,供大家学习一下

package com.example.administrator.retrofit_test

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.ViewGroup
import com.jiuhong.boyuan.utlis.UIUtils

/**
 * Created by Administrator on 2017/6/6.
 */

/*
*
*   流失布局,XINHAO_HAN
* */
class FlowLayout : ViewGroup {


    var conutSize: Int = 0

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    //测量位置
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        /*
               *
               * 表示当前没有孩子
               * */
        if (childCount == 0) {
            return
        }
        //记录当前所有孩子的宽度
        var childWei: Int = 0
        //记录当前多有孩子的高度
        var childHei: Int = 0
        //记录多少行
        var cout: Int = 0

        Log.e("屏幕宽度", "" + UIUtils.getWeiSize())


        for (i in 0..childCount - 1) {
            val childAt = getChildAt(i)
            val widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
            val heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
            childAt.measure(widthMeasureSpec, heightMeasureSpec)
            //相加当前孩子的宽高度

            Log.e("测量结果", "" + childWei)
            if (childWei < UIUtils.getWeiSize()) {
                //一行大小正好方的下,放不下就放到下一行,没毛病
                if (i == 0)
                    childAt.layout(0, (cout * childAt.measuredHeight), (childWei + childAt.measuredWidth), (cout * childAt.measuredHeight) + childAt.measuredHeight)
                else {
                    if (childWei + childAt.measuredWidth > UIUtils.getWeiSize()) {
                        //表示本行已无力吐槽,让给下一行
                        cout++
                        //记得下一行位置记录从0开始
                        childWei = 0
                        childAt.layout(childWei, (cout * childAt.measuredHeight), (childWei + childAt.measuredWidth), (cout * childAt.measuredHeight) + childAt.measuredHeight)
                    } else {
                        childAt.layout(childWei, (cout * childAt.measuredHeight), (childWei + childAt.measuredWidth), (cout * childAt.measuredHeight) + childAt.measuredHeight)
                    }
                }

                childWei += childAt.measuredWidth
            } else {
                //不能放下一行,需要换行

                //记录行数
                cout++
                //重新记录行数
                childWei = 0
            }


        }
        conutSize = cout


    }

    //测量大小,根据当前孩子View来决定自己的大小
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {


        /*
        *
        * 表示当前没有孩子
        * */
        if (childCount == 0) {
            return
        }
        var cout: Int = 0
        //记录当前所有孩子的宽度
        var childWei: Int = 0
        //记录当前多有孩子的高度
        var childHei: Int = 0


        for (i in 0..childCount - 1) {
            val childAt = getChildAt(i)
            childAt.measure(widthMeasureSpec, heightMeasureSpec)
            //相加当前孩子的宽高度
            childWei += childAt.measuredWidth
            childHei += childAt.measuredHeight
        }

        if (childWei > UIUtils.getWeiSize()) {
            childWei = UIUtils.getWeiSize()
        } else {

        }

        super.onMeasure(MeasureSpec.makeMeasureSpec(childWei, MeasureSpec.EXACTLY), heightMeasureSpec)
    }

}

案例2

package com.jiuhong.boyuan.view

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.RelativeLayout
import android.widget.TextView
import com.jiuhong.boyuan.R
import com.jiuhong.boyuan.adapter.ListBaseAdapter
import com.jiuhong.boyuan.utlis.UIUtils

/**
 * Created by Administrator on 2017/5/27.
 */


/*
*
*  快递自定义_快递刷新
* */

class LineViewKD : RelativeLayout {
    private var viewX: Int = 0
    private var viewY: Int = 0
    private var mid: Int = 0
    private var arrayListMessage: ArrayList? = null
    private var arrayListTime: ArrayList? = null
    private var arrListBean: ArrayList? = ArrayList()
    private var listView_view: ListView? = null
    private var message_order_tv: TextView? = null


    constructor(context: Context?) : super(context) {
        initData()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        initData()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initData()
    }

    //初始化控件

    private val view1: View?
        get() {
            val view = UIUtils.getView(R.layout.view_line_kd)
            return view
        }



    //传入数据 包括物流信息和物流单号
    fun setData(arrayListMessage: ArrayList?, arrayListTime: ArrayList?, order: String, wuliuBean: String) {


        //显示物流详细
        message_order_tv?.setText(UIUtils.CombinationString(wuliuBean, "(", order, ")"))
        if (arrayListMessage == null || arrayListTime == null) {
            return
        }
        this.arrayListMessage = arrayListMessage
        this.arrayListTime = arrayListTime

        if (arrayListMessage == null || arrayListTime == null) {
            throw RuntimeException("传入数据不能为空!")
        }
        for (a in arrayListMessage.indices) {
            var lineBean: LineBean = LineBean(arrayListMessage.get(a), arrayListTime.get(a))
            arrListBean?.add(lineBean)
        }

        listView_view?.adapter = MyAdapter(arrListBean)


        //量测
        val view1: View = UIUtils.getView(R.layout.item_view_kd)
        val hei: Int = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
        val wei: Int = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
        view1.measure(hei, wei)
        viewX = view1.measuredWidth
        viewY = view1.measuredHeight
        val listViewHei: Int = viewY * arrayListMessage.size as Int
        val vl: LinearLayout.LayoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        vl.height = listViewHei
        listView_view?.layoutParams = vl


        //listView_view?.adapter = LineViewKD.MyAdapter(arrListBean)


    }

    fun initData() {
        val view = view1
        listView_view = view?.findViewById(R.id.listView_view) as ListView
        message_order_tv = view?.findViewById(R.id.message_order_tv) as TextView
        addView(view)


    }

    //转换为目标数据
    data class LineBean(var message: String, var time: String)

    //设置Adapter
    class MyAdapter : ListBaseAdapter {

        constructor(list: MutableList?) : super(list)


        override fun initView(t: LineBean?, pos: Int, viewGroup: ViewGroup?, myViewHolder: MyViewHolder?) {
            var `this`: ThisViewHolder = myViewHolder as ThisViewHolder
            `this`.message_tv_kd?.setText(t?.message)
            `this`.time_tv_kd?.setText(t?.time)

            if (pos != 0) {
                `this`.get_stat1?.visibility = View.VISIBLE
                `this`.get_stat2?.visibility = View.GONE
                `this`.time_tv_kd?.setTextColor(Color.parseColor("#adadad"))
                `this`.message_tv_kd?.setTextColor(Color.parseColor("#adadad"))

            } else {
                `this`.get_stat1?.visibility = View.GONE
                `this`.get_stat2?.visibility = View.VISIBLE
                `this`.time_tv_kd?.setTextColor(Color.parseColor("#007dfd"))
                `this`.message_tv_kd?.setTextColor(Color.parseColor("#007dfd"))
            }
        }

        override fun getMyViewHolder(): MyViewHolder {
            return ThisViewHolder(UIUtils.getView(R.layout.item_view_kd))
        }


    }

    //设置ViewHolder
    class ThisViewHolder : ListBaseAdapter.MyViewHolder {
        var message_tv_kd: TextView? = null
        var time_tv_kd: TextView? = null
        //last
        var get_stat2: RelativeLayout? = null
        //runing
        var get_stat1: RelativeLayout? = null


        constructor(view: View?) : super(view) {
            message_tv_kd = findViewById(R.id.message_tv_kd) as TextView
            time_tv_kd = findViewById(R.id.time_tv_kd) as TextView
            get_stat2 = findViewById(R.id.get_stat2) as RelativeLayout
            get_stat1 = findViewById(R.id.get_stat1) as RelativeLayout
        }


    }


}

持续更新中

你可能感兴趣的:(Android Kotiln讲解)