One way to solve this problem is to manipulate the backing array so the RecyclerView
just doesn't know about the missing views. A second way is to assign a different view type with zero height to those positions that are missing. One type for visible positions and another for invisible ones. The following is an example adapter that implements this concept:
RecyclerViewAdapter.java
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<String> mItems;
RecyclerViewAdapter(List<String> items) {
mItems = items;
}
@Override
public @NonNull
RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view;
if (viewType == INVISIBLE_ITEM_TYPE) {
// The type is invisible, so just create a zero-height Space widget to hold the position.
view = new Space(parent.getContext());
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
} else {
view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
}
return new ItemViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
ItemViewHolder vh = (ItemViewHolder) holder;
String itemText = mItems.get(position);
if (vh.getItemViewType() == VISIBLE_ITEM_TYPE) {
// Only populate if a visible type.
vh.mItemTextView.setText(itemText);
int bgColor = (position % 2 == 0)
? android.R.color.holo_blue_light
: android.R.color.holo_green_light;
holder.itemView.setBackgroundColor(
holder.itemView.getContext().getResources().getColor(bgColor));
}
}
@Override
public int getItemCount() {
return (mItems == null) ? 0 : mItems.size();
}
@Override
public int getItemViewType(int position) {
// First 4 position don't show. The visibility of a position can be separately
// determined if only, say, the first and third position should be invisible.
return (position < 4) ? INVISIBLE_ITEM_TYPE : VISIBLE_ITEM_TYPE;
}
static class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView mItemTextView;
ItemViewHolder(View item) {
super(item);
mItemTextView = item.findViewById(android.R.id.text1);
}
}
private final static int VISIBLE_ITEM_TYPE = 1;
private final static int INVISIBLE_ITEM_TYPE = 2;
}
I would post a video, but it will just show the RecyclerView
starting at item #4.