我正在使用this code snippet
中的CursorRecyclerViewAdapter当我在recyclerview中使用单一视图类型时它工作正常。但是如果我使用多个视图类型,我会崩溃说int android.support.v7.widget.RecyclerView$ViewHolder.mItemViewType null object reference
我使用以下代码扩展CursorRecyclerViewAdapter
public class PostCursorAdapter extends CursorRecyclerViewAdapter<RecyclerView.ViewHolder> {
private static final int VIEW_HOLDER_TYPE_1=1;
private static final int VIEW_HOLDER_TYPE_2=2;
private Integer viewtype=0;
public PostCursorAdapter(Context context,Cursor cursor){
super(context,cursor);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, Cursor cursor) {
PostItem postitem = PostItem.fromCursor(cursor);
Log.d("PostItem",postitem.toString());
int viewtype=1;
if (postitem.isFromMe()==true){
viewtype=1;
}
else {
viewtype=2;
}
switch (viewtype) {
case VIEW_HOLDER_TYPE_1:
ViewHolder_Type1 viewholder1 = (ViewHolder_Type1) holder;
TextView mytimeView = (TextView) viewholder1.mytimeTextView;
mytimeView.setText(postitem.getPostTime());
TextView mymsgView = (TextView) viewholder1.mymessageTextView;
mymsgView.setText(postitem.getPostMsg());
break;
case VIEW_HOLDER_TYPE_2:
ViewHolder_Type2 viewholder2 = (ViewHolder_Type2) holder;
TextView timeView = (TextView) viewholder2.timeTextView;
timeView.setText(postitem.getPostTime());
TextView msgView = (TextView) viewholder2.messageTextView;
msgView.setText(postitem.getPostMsg());
break;
default:
break;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
switch (viewType) {
case VIEW_HOLDER_TYPE_1:
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.mypost, parent, false);
ViewHolder_Type1 vh1 = new ViewHolder_Type1(v);
return vh1;
case VIEW_HOLDER_TYPE_2:
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post, parent, false);
ViewHolder_Type2 vh2 = new ViewHolder_Type2(v);
return vh2;
default:
break;
}
return null;
}
public static class ViewHolder_Type1 extends RecyclerView.ViewHolder {
public TextView mymessageTextView, mytimeTextView;
public ViewHolder_Type1(View v) {
super(v);
this.mymessageTextView = (TextView) v.findViewById(R.id.mymessageTextView);
this.mytimeTextView = (TextView) v.findViewById(R.id.mytimeTextView);
}
}
public static class ViewHolder_Type2 extends RecyclerView.ViewHolder {
public TextView messageTextView, timeTextView;
public ViewHolder_Type2(View v) {
super(v);
this.messageTextView = (TextView) v.findViewById(R.id.messageTextView);
this.timeTextView = (TextView) v.findViewById(R.id.timeTextView);
}
}}
答案 0 :(得分:0)
问题(我认为)是RecyclerView没有任何线索,你有多种视图类型。
解决方案可能是覆盖getItemViewType
。但是,当您只能从Cursor中决定viewType时,这可能会很棘手。如果是这种情况,我建议您覆盖GetItemViewType
类中的CursorRecyclerViewAdapter
方法。
@Override
public int getItemViewType(int position){
int viewType = cursor // somehow determine the viewType;
return viewType;
}
答案 1 :(得分:-1)
您应该实现getItemViewType
以返回Recycler视图中每个位置的正确ViewType。请参阅教程here。