我正在使用
Android架构组件
example中的DataBoundListAdapter.
我需要增强它以支持多种项目类型.有人做过吗?
我的问题是如何在createBinding过程中找到项目类型,因为我没有可用的项目位置,但是我需要它来获取项目类型以便能够基于它来扩展正确的布局.
@Override
protected ChatMessageItemBinding createBinding(ViewGroup parent) {
MyItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.my_item, parent,
false, dataBindingComponent);
return binding;
}
最佳答案 查看
DataBoundListAdapter的源代码,我可以看到创建绑定只是来自onCreateViewHolder的调用,它包含了您需要的信息 – viewType:Int
最简单的选项是覆盖方法在您自己的适配器中执行的操作,以传递您需要的类型信息.
@Override
DataBoundViewHolder<V> onCreateViewHolder(ViewGroup parent, int viewType) {
//Note: no call to super
V binding = createBindingByType(parent, viewType) //this is a new method
return DataBoundViewHolder(binding)
}
private ChatMessageItemBinding createBindingByType(ViewGroup parent, int viewType) {
@LayoutRes int layout;
switch(viewType) {
case ...:
layout = R.layout.my_item;
break;
...
}
return DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), layout, parent, false, dataBindingComponent);
}
@Override
protected ChatMessageItemBinding createBinding(ViewGroup parent) {
throw new RuntimeException("This method should not be called with MyAdapter");
}