我在下面有一个RecyclerView.Adapter。适配器在没有ItemDiscussionListHeaderBinding的情况下工作正常,但是一旦添加了它,使用两个视图类型,我得到了一个Java.lang.RuntimeException:视图标签在视图上是不正确的:null。为什么会这样?
在我的Adapter.java中:
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case BODY:
ItemDiscussionListBodyBinding bodyBinding = DataBindingUtil.inflate(inflater, R.layout.item_discussion_list_body, parent, false);
return new DiscussionListItemBodyViewHolder(bodyBinding);
case HEADER:
ItemDiscussionListHeaderBinding headerBinding = DataBindingUtil.inflate(inflater, R.layout.item_discussion_list_header, parent, false);
return new DiscussionListItemHeaderViewHolder(headerBinding);
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Discussion discussion = mDiscussions.get(position);
switch (holder.getItemViewType()) {
case BODY:
((DiscussionListItemBodyViewHolder) holder).bind(discussion);
break;
case HEADER:
((DiscussionListItemHeaderViewHolder) holder).setHeader("My Discussions");
break;
}
}
@Override
public int getItemCount() {
return mDiscussions.size();
}
@Override
public int getItemViewType(int position) {
if (position == 0) {
return HEADER;
}
return BODY;
}
在我的两个观看者中:
class DiscussionListItemBodyViewHolder extends RecyclerView.ViewHolder {
private ItemDiscussionListBodyBinding mBinding;
DiscussionListItemBodyViewHolder(ItemDiscussionListBodyBinding binding) {
super(binding.getRoot());
mBinding = binding;
}
void bind(Discussion discussion) { // do whatever }
class DiscussionListItemHeaderViewHolder extends RecyclerView.ViewHolder {
private ItemDiscussionListHeaderBinding mBinding;
DiscussionListItemHeaderViewHolder(ItemDiscussionListHeaderBinding binding) {
super(binding.getRoot());
mBinding = binding;
}
void setHeader(String header) { // do whatever }
我已将错误缩小到标题绑定,而不是正文绑定,这里是xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@color/lighter_gray"
android:paddingBottom="8dp"
android:paddingLeft="14dp"
android:paddingRight="14dp"
android:paddingTop="8dp">
<TextView
android:id="@+id/item_discussion_list_header_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Classes" />
</LinearLayout>