Kotlin编程

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

2017-07-15  本文已影响58人  Derek_Yan

<h4>7、${} 正确使用方法</h4>
一个DataBean实体类,想要打印其中一个属性值

<h4>6、RxJava+Retrofit中Service定义时可变Url @Path("")语法</h4>
<p><code>
/**
* @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<Result<List<GirlBean>>></code></p>

<h4>5、BaseRecyclerViewAdapter封装</h4>
<p><code>abstract class BaseRecyclerViewAdapter<D, VH : BaseRecyclerViewAdapter.BaseViewHolder>(layoutResId: Int, data: MutableList<D>) : RecyclerView.Adapter<VH>() {

open var layoutResId: Int = 0 //item资源Id
open var data: List<D> = 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
    }
}

}
</code></p>
<p>在Activity中定义MyRecyclerViewAdapter</p>
<p><code>
inner class MyRecyclerViewAdapter<VH: MyViewHolder>(layoutResId: Int, data: MutableList<GirlBean>) : BaseRecyclerViewAdapter<GirlBean, VH>(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) {
        this@MainActivity.loadImg(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?
    }
}</code></p>

<p>初始化时使用</p>
<p><code>
mAdapter = MyRecyclerViewAdapter(R.layout.item_girl,mList)
recyclerview.adapter = mAdapter

</code></p>

<h4>4、new一个对象(举例Runnable)</h4>
val mRunnable = object : Runable { }
最后大括号使用lambda

<h4>3、单例实现</h4>
<code> companion object{
fun getInstance(): SPUtil {
return Inner.instance
}
}
private object Inner{
val instance = SPUtil()
}</code>
调用:SPUtil.getInstance

<h4>2、Map使用</h4>
kotlin中Map是val不可变类型,所以没有put方法
解决方法使用MutableMap可变类型

<h4>1、跳转Activity</h4>
startActivity(Intent(this, MainActivity::class.java))
注意:使用::反射class类

上一篇下一篇

猜你喜欢

热点阅读