Android在RecyclerView for DataBinding功能上使用多个不同的行

时间:2017-03-15 17:59:36

标签: android data-binding android-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);
}

1 个答案:

答案 0 :(得分:4)

您正在尝试在实例化视图持有者之前绑定适配器的视图。视图绑定应在onBindViewHolder()中执行。

创建一个扩展RecyclerView.ViewHolder的基本视图持有者类,并具有ShowBookItemsViewHolderRobotViewHolder实现的抽象绑定(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>