具体方法在demo中
主要是实现思路看代码
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == NO_IMAGES) {
View view = LayoutInflater.from(context).inflate(R.layout.item_home_news_details_no_images, parent, false);
return new ViewHolders(view);
} else if (viewType == AD) {
View view = LayoutInflater.from(context).inflate(R.layout.item_ad, parent, false);
return new ViewHolderAd(view);
} else {
View view = LayoutInflater.from(context).inflate(R.layout.item_home_news_details_no_images, parent, false);
return new ViewHolders(view);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ViewHolders) {
int pos = getRealPosition(holder);
ViewHolders mViewHolders = (ViewHolders) holder;
mViewHolders.setItems(name[pos]);
mViewHolders.refreshView();
} else if (holder instanceof ViewHolderAd) {
ViewHolderAd holderAd = (ViewHolderAd) holder;
holderAd.setItems(imgs[(position - 1) / 3]);
holderAd.refreshView();
}
}
int getRealPosition(RecyclerView.ViewHolder holder) {
int position = holder.getLayoutPosition();
int i = position / 3;
if (i < imgs.length) {
return position - i;
} else {
return position;
}
}
@Override
public int getItemCount() {
return getContentItemCount();
}
/**
* 判断当前item是否是HeadView
*
* @param position 因为和五求余所以第0位也会是广告位 所以需要给他位置+1
* @return
*/
public boolean isHeaderView(int position) {
return (position + 1) % 3 == 0 && position /3 < imgs.length;
}
public int getContentItemCount() {
return name == null ? 0 : name.length;
}
@Override
public int getItemViewType(int position) {
if (position == 0) {
return NO_IMAGES;
}
if (isHeaderView(position)) {
return AD;
} else {
return NO_IMAGES;
}
}