如何利用 Anko 扩展 RecyclerView 或 Cust
2017-08-10 本文已影响915人
关内侯和他的五百勇士
前言
Anko 作为 jetbrain 同时推出的辅助 kotlin 的神兵利器,可以使用 DSL 语言来快速的完成 android 布局。
从此可以完全抛弃 xml了。anko 默认扩展了LinearLayout(verticalLayout,没有 horizontalLayout,可以使用 orientation 来定义),relativeLayout 等,
但对于 RecyclerView 或者 自定义的 View 没有支持。
所以想要在代码中使用他们,就需要 anko extension,这里简单的扩展一下 RecyclerView
1.添加依赖
compile 'com.android.support:recyclerview-v7:$support_version'
// Anko Layouts
compile "org.jetbrains.anko:anko-sdk25:$anko_version" // sdk15, sdk19, sdk21, sdk23 are also available
compile "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
// Coroutine listeners for Anko Layouts(可以在 DSL 中直接使用协程)
compile "org.jetbrains.anko:anko-sdk25-coroutines:$anko_version"
compile "org.jetbrains.anko:anko-appcompat-v7-coroutines:$anko_version"
2. 扩展
inline fun ViewManager.recyclerView() = RecyclerView(Application.instance,null,-1)
inline fun ViewManager.recyclerView(init: RecyclerView.() -> Unit): RecyclerView {
return ankoView({RecyclerView(Application.instance,null)},0,init)
}
ViewManager 是 package android.view; 中的一个 interface:
interface to let you add and remove child views to an activity: 一个可以向 activity 中添加删除 view 的接口

然后通过 ankoView 来创建 View

3.食用
val items = arrayListOf<String>()
items.add("OneRepublic")
items.add("LinkinPark")
items.add("ColdPlay")
items.add("Maroon5")
items.add("ImageDragon")
recyclerView {
layoutManager = LinearLayoutManager(this@LayoutActivity)
adapter = myAdapter(items)
(adapter as myAdapter).setOnItemClcickListener(object : myAdapter.OnItemClickListener {
override fun onItemClicked(v: View, position: Int) {
toast(items[position])
}
})
}.lparams(width = matchParent) {
height = matchParent
}
/**
* adapter for recycler
*/
class myAdapter(val items: ArrayList<String>?) : RecyclerView.Adapter<myAdapter.myHolder>() {
override fun onBindViewHolder(holder: myHolder?, position: Int) {
val tv = holder?.itemView as TextView
tv.text = items!![position]
tv.onClick { mOnItemClcickListener!!.onItemClicked(it!!, position) }
}
override fun getItemCount(): Int {
return items?.size ?: 0
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): myHolder {
val tv = TextView(parent?.context)
tv.gravity = Gravity.CENTER
tv.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
tv.padding = parent?.context!!.dip(10)
tv.textSize = parent?.context!!.sp(24).toFloat()
tv.textColor = Color.RED
return myHolder(tv)
}
fun setOnItemClcickListener(listener: OnItemClickListener) {
mOnItemClcickListener = listener
}
interface OnItemClickListener {
fun onItemClicked(v: View, position: Int)
}
var mOnItemClcickListener: OnItemClickListener? = null
inner class myHolder(itemView: View?) : RecyclerView.ViewHolder(itemView)
}