Android在RecyclerView for DataBinding功能上使用多个不同的行
作者:互联网
基本上我可以在recyclerview adaper上使用多行而没有任何问题,例如这段代码:
@Override
public ShowBookItemsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layout = -1;
switch (viewType) {
case 1:
layout = R.layout.item_heading_one;
break;
case 2:
layout = R.layout.item_heading_two;
break;
}
View v = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);
ShowBookItemsViewHolder holder = new ShowBookItemsViewHolder(v);
return holder;
}
现在我正在尝试使用此功能,当我使用DataBinding,但我得到一个错误,我不能这样做
这是我的错误代码:
@Override
public RobotViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layout = -1;
if (inflater == null) {
switch (viewType) {
case 0:
layout = R.layout.robot_item_action;
break;
case 1:
layout = R.layout.robot_user_action;
break;
}
inflater = LayoutInflater.from(parent.getContext());
}
RobotDataBinding dataBinding = RobotDataBinding.inflate(layout, parent, false);
return new RobotViewHolder(dataBinding);
}
解决方法:
您正试图在实例化视图持有者之前绑定适配器的视图.视图绑定应在onBindViewHolder()中执行.
创建一个扩展RecyclerView.ViewHolder的基本视图持有者类,并具有ShowBookItemsViewHolder和RobotViewHolder实现的抽象绑定(Object obj)方法.感谢George Mount的这种方法.
public abstract class BaseViewHolder extends RecyclerView.ViewHolder {
...
// delegate binding to child class
protected abstract void bind(Object obj);
}
然后在onBindViewHolder()中:
public void onBindViewHolder(BaseViewHolder holder, int position) {
holder.bind(adapterData.get(position)
}
这会将您的adapterData对象传递给子视图持有者以进行绑定:
public class ShowBookItemsViewHolder extends BaseViewHolder {
...
public void bind(Object obj) {
// Bind here...
}
}
重写getItemViewType()以使用不同的视图类型提供onCreateViewHolder().例如:
public int getItemViewType(int position) {
// Change layout every other position
return position % 2 == 0 ? 0 : 1;
}
使用视图类型构建视图持有者:
public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 0) {
return new ShowBookItemsViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.your_layout, parent, false)
else {
return new RobotViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.your_layout, parent, false)
}
}
确保onCreateViewHolder()返回基本视图持有者,并且适配器类扩展了RecyclerView.Adapter< YourAdapter.YourBaseViewHolder>.
标签:android,data-binding,android-databinding 来源: https://codeday.me/bug/20191008/1875091.html