Skip to content

Instantly share code, notes, and snippets.

@keinix
Created September 21, 2018 07:01
Show Gist options
  • Save keinix/46848bd52117f533c26b20300ba6abda to your computer and use it in GitHub Desktop.
Save keinix/46848bd52117f533c26b20300ba6abda to your computer and use it in GitHub Desktop.
public class LiteratureAdapter extends RecyclerView.Adapter {
private List<Literature> mLiteratureList;
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView;
switch (viewType) {
case Literature.TYPE_BOOK:
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.your_layout, parent, false);
return new BookViewHolder(itemView);
case Literature.TYPE_MAGAZINE:
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.your_layout, parent, false);
return new MagazineViewHolder(itemView);
default: // TYPE_NEWSPAPER
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.your_layout, parent, false);
return new NewspaperViewHolder(itemView);
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case Literature.TYPE_BOOK:
((BookViewHolder) holder).bindView(position);
break;
case Literature.TYPE_MAGAZINE:
((MagazineViewHolder) holder).bindView(position);
break;
case Literature.TYPE_NEWSPAPER:
((NewspaperViewHolder) holder).bindView(position);
break;
}
}
@Override
public int getItemCount() {
if (mLiteratureList == null) {
return 0;
} else {
return mLiteratureList.size();
}
}
@Override
public int getItemViewType(int position) {
return mLiteratureList.get(position).getType();
}
public void setLiteratureList(List<? extends Literature> literatureList) {
if (mLiteratureList == null){
mLiteratureList = new ArrayList<>();
}
mLiteratureList.clear();
mLiteratureList.addAll(literatureList);
notifyDataSetChanged();
}
class BookViewHolder extends RecyclerView.ViewHolder {
public BookViewHolder(View itemView) {
super(itemView);
// get reference to views
// itemView.findViewById...
}
void bindView(int position) {
Book book = (Book) mLiteratureList.get(position);
// bind data to the views
// textView.setText()...
}
}
class MagazineViewHolder extends RecyclerView.ViewHolder {
public MagazineViewHolder(View itemView) {
super(itemView);
// get reference to views
}
void bindView(int position) {
Magazine magazine = (Magazine) mLiteratureList.get(position);
// bind data to the views
}
}
class NewspaperViewHolder extends RecyclerView.ViewHolder {
public NewspaperViewHolder(View itemView) {
super(itemView);
// get reference to views
}
void bindView(int position) {
Newspaper newspaper = (Newspaper) mLiteratureList.get(position);
// bind data to the views
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment