Kotlin 重写项目笔记(持续更新)

7、${} 正确使用方法


一个DataBean实体类,想要打印其中一个属性值

  • println("sth $databean.name") 这是错误的写法 带"."的都属于表达式 必须用"{}"包起来不然它会打印出 "sth @databean对象值 .name"
  • println("sth ${databean.name}") 这才是正确写法

6、RxJava+Retrofit中Service定义时可变Url @Path("")语法



/**
* @param type 资源类型
* @param pageNum 每页数量
* @param type 页数
*/
@GET("data/{type}/{count}/{pageNum}")
fun getGirls(@Path("type") s: String,
@Path("count") count: Int,
@Path("pageNum") pageNum: Int ): Observable>>

5、BaseRecyclerViewAdapter封装


abstract class BaseRecyclerViewAdapter(layoutResId: Int, data: MutableList) : RecyclerView.Adapter() {

open var layoutResId: Int = 0 //item资源Id
open var data: List = data //数据集合
open var view: View? = null

init {
    if (layoutResId != 0)
        this.layoutResId = layoutResId
    else
        throw NullPointerException("请设置Item资源Id")
}

override fun onBindViewHolder(holder: VH, position: Int) {
    bindData(holder, data[position],position)
}

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

/**
 * 绑定数据
 * @param  holder
 * *
 * @param data
 */
protected abstract fun bindData(holder: VH, data: D,position: Int)

open class BaseViewHolder : RecyclerView.ViewHolder{
    open var mView: View? = null
    constructor(view: View): super(view){
        mView = view
    }
}

}


在Activity中定义MyRecyclerViewAdapter



inner class MyRecyclerViewAdapter(layoutResId: Int, data: MutableList) : BaseRecyclerViewAdapter(layoutResId, data) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        view = LayoutInflater.from(parent.context).inflate(layoutResId, parent, false)
        return MyViewHolder(view!!) as VH
    }

    override fun bindData(holder: VH, data: GirlBean,position: Int) {
        [email protected](data.url,holder.imageview!!)
        holder.textview?.text = data.who
        loadImg(data.url, holder.imageview!!)
        holder.imageview?.setOnClickListener { mListener.onItemClick(position, holder.imageview!!) }
    }
}

inner class MyViewHolder(view: View) : BaseRecyclerViewAdapter.BaseViewHolder(view) {
    var imageview: ImageView? = null
    var textview: TextView? = null
    init {
        imageview = mView?.findViewById(R.id.imageview) as ImageView?
        textview = mView?.findViewById(R.id.textview) as TextView?
    }
}

初始化时使用



mAdapter = MyRecyclerViewAdapter(R.layout.item_girl,mList)
recyclerview.adapter = mAdapter

4、new一个对象(举例Runnable)


val mRunnable = object : Runable { }
最后大括号使用lambda

3、单例实现


companion object{
fun getInstance(): SPUtil {
return Inner.instance
}
}
private object Inner{
val instance = SPUtil()
}

调用:SPUtil.getInstance

2、Map使用


kotlin中Map是val不可变类型,所以没有put方法
解决方法使用MutableMap可变类型

1、跳转Activity


startActivity(Intent(this, MainActivity::class.java))
注意:使用::反射class类

你可能感兴趣的:(Kotlin 重写项目笔记(持续更新))