我正在为任何类型的绑定创建通用适配器。
class DataBindingBaseAdapter<T> : RecyclerView.Adapter<DataBindingViewHolder<T>> {
private var listItems: List<T>
private var layoutID: Int
constructor(layoutID: Int,listItems: List<T>) {
this.listItems = listItems
this.layoutID = layoutID
}
override fun onCreateViewHolder(parent: ViewGroup, p1: Int): DataBindingViewHolder<T> {
val binding = DataBindingUtil.inflate<ViewDataBinding>(LayoutInflater.from(parent.context),
layoutID,parent,false)
return DataBindingViewHolder(binding)
}
override fun getItemCount(): Int {
return listItems.size
}
override fun onBindViewHolder(holder: DataBindingViewHolder<T>, pos: Int) {
holder.bindData(listItems.get(pos))
}
}
DataBindingViewHolder.kt
class DataBindingViewHolder<T>(val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {
fun bindData(model : T){
binding.setVariable(BR.user,model)
binding.executePendingBindings()
}
}
TestListActivity.kt
class TestListActivity : AppCompatActivity() {
val userList: MutableList<User> = mutableListOf(
User("FirstName", "LastName"), User("FirstName2", "LastName")
, User("FirstName3", "LastName"), User("FirstName4", "LastName"), User("FirstName5", "LastName"),
User("FirstName6", "LastName"), User("FirstName", "LastName")
)
val personList: MutableList<Person> = mutableListOf(
Person("PersonName -> 1"), Person("FirstName2")
, Person("PersonName -> 3"), Person("FirstName2"), Person("FirstName"), Person("FirstName2")
, Person("PersonName -> 6"), Person("FirstName2")
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test_list)
recyclerView.apply {
layoutManager = LinearLayoutManager(this@TestListActivity)
//adapter = DataBindingBaseAdapter<User>(R.layout.item_row, userList);
adapter = DataBindingBaseAdapter<Person>(R.layout.item_person, personList);
}
}
}
是否可以将任何通用变量发送到DataBindingViewHolder
binding.setVariable(BR.user,model) //for each type of Model it is BR.person and BR.user.
是否有任何Generic variable
。或者我必须在适配器中传递此paramter
并在DataBindingViewHolder
中获得它
我们通常必须在RecyclerView中显示项目列表。如果可能的话,那将是非常惊人的。还有另一件事,如果我将变量BR.user或BR.person用作适配器参数并将其设置在DataBindingViewHolder
是否存在任何性能问题?