基本上我可以在recyclervIEw adaper上使用多行而没有任何问题,例如这段代码:
@OverrIDepublic 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,但我得到一个错误,我不能这样做
这是我的错误代码:
@OverrIDepublic 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在RecyclerView for DataBinding功能上使用多个不同的行全部内容,希望文章能够帮你解决Android在RecyclerView for DataBinding功能上使用多个不同的行所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)