[databinding]RecyclerView+databinding+kotlin

阅读更多

一.数据:

User:

class User {

    var firstname: ObservableField = ObservableField()
    var lastname: ObservableField = ObservableField()
    var isAdult: ObservableBoolean = ObservableBoolean()
    var displayName: ObservableField = ObservableField()
    var age: ObservableField = ObservableField()

}

 

二.item view:

recycler_view_item.xml:


    
        
    
    
        
        
    

 

三.Adapter:

class RecyclerViewAdapter(private var userList: MutableList) : RecyclerView.Adapter() {

    override fun getItemCount(): Int  = userList.size

    override fun onBindViewHolder(holder: TestViewHolder?, position: Int) {
        holder?.bind(userList[position])
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): TestViewHolder {
        val binding = DataBindingUtil.inflate(
                LayoutInflater.from(parent?.context),
                R.layout.recycler_view_item,
                parent,
                false
        )
        return TestViewHolder(binding)
    }


    class TestViewHolder(private val binding: RecyclerViewItemBinding) 
                   : ViewHolder(binding.root) {
        fun bind(data: User) {
              //方法一:
//            binding.setVariable(BR.user,data)
            //方法二:
            binding.user = data
            binding.executePendingBindings()
        }
    }
}

 

四.Activity:

class RecycleViewActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recycle_view)

        val layoutManager = LinearLayoutManager(this)
        recycler_view.layoutManager = layoutManager
        recycler_view.adapter = RecyclerViewAdapter(initUsers())

    }

    private fun initUsers() : MutableList{
        val userList = mutableListOf()
        for (i in 1..5) {
            var user = User()
            user.firstname.set("name $i")
            user.age.set(i)
            userList.add(user)
        }
        return userList
    }
}

 

参考:

1.java+RecyclerView:https://www.cnblogs.com/DoNetCoder/p/7243878.html?utm_source=tuicool&utm_medium=referral

2.kotlin+RecyclerView:https://github.com/JetBrains/kotlin-examples/blob/master/gradle/android-databinding/app/src/main/java/org/example/kotlin/databinding/OtherActivity.kt

你可能感兴趣的:(RecyclerView,kotlin,databinding)