美文网首页
Kotlin中RecyclerView的BaseQuickAda

Kotlin中RecyclerView的BaseQuickAda

作者: 因为我的心 | 来源:发表于2021-08-03 13:45 被阅读0次

    1、相关依赖

    allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }
    
    dependencies {
        implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.4'
    }
    

    官网链接

    2、使用androidx扩展包下的recycleview

    <androidx.recyclerview.widget.RecyclerView
                            android:id="@+id/recycler_view"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">
                        </androidx.recyclerview.widget.RecyclerView>
    

    3、BaseQuickAdapter

    //注意:参数1:layoutResId;参数2: data:MutableList<Bean>? = null
    //(layoutResId,data)必须这样写
    class MYAdapter(
        layoutResId:Int,
        data:MutableList<Bean>? = null
    ): BaseQuickAdapter<Bean, BaseViewHolder>(layoutResId,data){
        override fun convert(helper: BaseViewHolder, item: Bean?) {
            item?.let {
                helper.setText(R.id.tv_start_time,item?.startTime)
                      .setText(R.id.tv_week_day,item?.weekDay)
            }
        }
    }
    

    4、adapter初始化

     private val myAdapter by lazy {
        
            var bean1 = StartTimeBean("07:45","星期一",false)
            var bean2 = StartTimeBean("09:45","星期二",false)
            var bean3 = StartTimeBean("08:45","星期三",true)
         
            carList.add(bean1)
            carList.add(bean2)
            carList.add(bean3)
       
            StartTimeAdapter(R.layout.item)
        }
    

    5、给子item添加点击事件

    var carList = mutableListOf<Bean>()
     mBinding.recyclerView.layoutManager = LinearLayoutManager(this)
            mBinding.recyclerView.adapter = myAdapter
            myAdapter?.setNewData(carList)
            //添加子View的点击事件
            myAdapter.addChildClickViewIds(R.id.switch_start)
            //事件回调
            myAdapter.setOnItemChildClickListener {
                    adapter, view, position ->
                        if (view.id == R.id.switch_start){
                            var switch_start:Switch = view as Switch
                            if (switch_start.isChecked){
                                ToastUtils.s(application,"选中$position")
                            }else{
                                ToastUtils.s(application,"取消$position")
                            }
    
                        }
            }
    

    6、BRVH所有文档

    相关文章

      网友评论

          本文标题:Kotlin中RecyclerView的BaseQuickAda

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