我的ViewHolder
适配器中只有一个RecyclerView
类:
public static class PlayerItemViewHolder extends RecyclerView.ViewHolder {
public ImageView news_image;
public TextView news_title;
public PlayerItemViewHolder(View view) {
super(view);
news_image = (ImageView) view.findViewById(R.id.news_image);
news_title = (TextView) view.findViewById(R.id.news_title);
}
}
@Override
public PlayerAdapter.PlayerItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View item_view = layoutInflater.inflate(R.layout.player_news_item, parent, false);
return new PlayerItemViewHolder(item_view);
}
@Override
public void onBindViewHolder(final PlayerAdapter.PlayerItemViewHolder viewHolder, Cursor cursor) {
Log.d("id", viewHolder.getItemId()+"");
Log.d("view_type", viewHolder.getItemViewType()+"");
Log.d("class", viewHolder.getClass().toString());
}
当我运行此代码时:
08-27 15:57:03.414 19971-19971/? D/id: 0
08-27 15:57:03.414 19971-19971/? D/view_type: 1
08-27 15:57:03.414 19971-19971/? D/class: class io.github.nekotachi.easynews.ui.adapter.PlayerAdapter$PlayerItemViewHolder
08-27 15:57:03.421 19971-19971/? D/id: 0
08-27 15:57:03.421 19971-19971/? D/view_type: 2
08-27 15:57:03.421 19971-19971/? D/class: class io.github.nekotachi.easynews.ui.adapter.PlayerAdapter$PlayerItemViewHolder
最后,它会导致错误:
java.lang.IllegalStateException: Two different ViewHolders have the same stable ID. Stable IDs in your adapter MUST BE unique and SHOULD NOT change.
在这种情况下,我认为视图类型应该相同,因为它们具有相同的类。而且, id 也应该不同。
答案 0 :(得分:1)
我猜你在ViewType
RecyclerView
函数中为你的观点传递了不同的getItemViewType
。
如果您从ViewType
返回不同的getItemViewType
,那么您需要在ViewType
内处理onBindViewHolder
,并同时使用不同的ViewHolder
类型。
例如,您有两个不同的ViewType
。这两个可以有相同的布局。但是你需要像这样为每个人指定一个ViewHolder
。
// For view_type = 1
private class FirstItemViewHolder extends ViewHolder {
public FirstItemViewHolder(View itemView) {
super(itemView);
}
}
// For view_type = 2
private class SecondItemViewHolder extends ViewHolder {
public SecondItemViewHolder(View itemView) {
super(itemView);
}
}
现在,您可以通过getItemViewType
方法像往常一样返回ViewType
。
@Override
public int getItemViewType(int position) {
if(returnFirstViewType()){
return VIEW_TYPE_1;
} else {
return VIEW_TYPE_2;
}
return super.getItemViewType(position);
}
现在,当您在onBindViewHolder
方法中绑定每个视图持有者时,您需要首先检查ViewType
,然后您需要执行此类其他操作。
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try {
if (holder instanceof FirstItemViewHolder) {
FirstItemViewHolder vh = (FirstItemViewHolder) holder;
// Code for view_type = 1 goes here
} else {
// Code for view_type = 2 goes here
}
} catch (Exception e) {
e.printStackTrace();
}
}