美文网首页
DataBinding笔记6

DataBinding笔记6

作者: satisfying | 来源:发表于2020-08-11 22:42 被阅读0次

    RecyclerView

    1.adapter 部分 通用的adapter

    data class BindingRecyclerViewHolder(val binding:ViewDataBinding) : RecyclerView.ViewHolder(binding.root)
    
    abstract class BindingRecyclerAdapter<T>(private val context: Context, private val layoutId:Int, var list:ArrayList<T>): RecyclerView.Adapter<BindingRecyclerViewHolder>() {
        override fun getItemCount(): Int {
            return list?.size ?: 0
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingRecyclerViewHolder {
            val binding=DataBindingUtil.inflate<ViewDataBinding>(LayoutInflater.from(context),layoutId,parent,false)
            return BindingRecyclerViewHolder(binding)
        }
        override fun onBindViewHolder(holder: BindingRecyclerViewHolder, position: Int) {
            holder.itemView.tag = position
            convert(holder, list[position], position)
        }
        /**
         * 填充RecyclerView适配器的方法,子类需要重写
         *
         * @param holder   ViewHolder
         * @param item     子项
         * @param position 位置
         */
        abstract fun convert(holder: BindingRecyclerViewHolder?, item: T, position: Int)
    
    }
    

    activity.xml

    <import type="com.example.databinding.BindingRecyclerAdapter"/>
    <variable
       name="recyclerAdapter"
       type="BindingRecyclerAdapter" />
    
    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:adapter="@{recyclerAdapter}"
       />
    

    activity

      val radapter=object:BindingRecyclerAdapter<House>(this,R.layout.item_recycler,houses){
          override fun convert(holder: BindingRecyclerViewHolder?, item: House, position: Int) {
                    holder?.binding?.setVariable(BR.house_info,item)
                    holder?.binding?.executePendingBindings()
                }
            }
       bindingBinding.recyclerAdapter=radapter
       radapter.notifyDataSetChanged()
    

    House

    class House {
        var address: ObservableField<String> = ObservableField<String>()
        var size: ObservableInt = ObservableInt()
        var number: ObservableField<String> = ObservableField<String>()
    }
    

    相关文章

      网友评论

          本文标题:DataBinding笔记6

          本文链接:https://www.haomeiwen.com/subject/qxsudktx.html