主要功能是在RecyclerView的尾部添加一个固定按钮,那么就要采用布局多类型的方式。
多种类型的item的如何实现呢?
(1)重写方法getItemViewType()来返回与上一个布局的不同的viewType值;
(2)在onCreateViewHolder中,根据不同的viewType来加载不同的布局,创建不同的viewHolder;
(3)通过添加1来更新getCount()的返回值;
(4)区分onBindViewHolder中两种类型的viewHolder(例如,使用instanceof)
以上四个函数的执行顺序分别为:
getItemCount()、getItemViewType()、onCreateViewHolder()、onBindViewHolder()
在getItemViewType()这个方法中对position做了一些判断。然后就是在onCreateViewHolder中具体的为每一种类型引入其对应的布局:
不要忘记通过添加1来更新getCount()的返回值,并区分OnBindViewHolder中的两种类型的ViewHolder(例如,使用instanceof)
public class AlbumPanoramaAdapter extends RecyclerView.Adapter {
//尾部默认按钮
private final int DEFAULT_ADD_VIEW = 1;
//常规布局
private final int ALBUM_DATA_VIEW = 2;
private Context context;
public AlbumPanoramaAdapter(Context context) {
this.context = context;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == DEFAULT_ADD_VIEW) {
View inflate = LayoutInflater.from(context).inflate(R.layout.item_album_panorama_default_view, parent, false);
return new DefaultAddViewViewHolder(inflate);
} else {
View inflate = LayoutInflater.from(context).inflate(R.layout.item_album_pannorama_view, parent, false);
return new AlbumPanoramaViewHolder(inflate);
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (holder instanceof AlbumPanoramaViewHolder) {
((AlbumPanoramaViewHolder) holder).mTvAblumPanoramaPhotoType.setText("");
} else if (holder instanceof DefaultAddViewViewHolder) {
// to do
}
}
@Override
public int getItemCount() {
return panoramaDataBeanList.size() + 1;
}
@Override
public int getItemViewType(int position) {
return (position == panoramaDataBeanList.size()) ? DEFAULT_ADD_VIEW : ALBUM_DATA_VIEW;
}
public void setAlbumPanoramaPhotoData(List<AlbumPanoramaDataBean> albumPanoramaDataBeanList) {
this.panoramaDataBeanList = albumPanoramaDataBeanList;
notifyDataSetChanged();
}
public class DefaultAddViewViewHolder extends RecyclerView.ViewHolder {
public LinearLayout mLyDefaultAddView;
public DefaultAddViewViewHolder(@NonNull View itemView) {
super(itemView);
mLyDefaultAddView = itemView.findViewById(R.id.ly_default_add_view);
}
}
public class AlbumPanoramaViewHolder extends RecyclerView.ViewHolder {
public ImageView mIvAblumPanoramaPhoto;
public AlbumPanoramaViewHolder(@NonNull View itemView) {
super(itemView);
mIvAblumPanoramaPhoto = itemView.findViewById(R.id.iv_ablum_panorama_photo);
}
}
}
网友评论