RecyclerView row's data gets jumbled when scrolling - android

I have a recycler view that shows transaction information. everything works good when its loaded but after scrolling a bit, contents of different rows gets mixed up.
Here is my code:
public TransactionAdapter.VHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.cell_transaction_history,parent,false);
VHolder holder = new VHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull TransactionAdapter.VHolder holder, int position) {
final Transaction transaction = transactionList.get(position);
holder.setData(transaction);
}
#Override
public int getItemCount() {
return transactionList.size();
}
private void setTransactionList(ArrayList<Transaction> transactions) {
this.transactionList = transactions;
}
And the ViewHolder:
private class VHolder extends RecyclerView.ViewHolder {
private AppCompatTextView schemeName;
private AppCompatTextView amount;
private AppCompatTextView bank;
private AppCompatTextView date;
private AppCompatTextView status;
VHolder(View itemView) {
super(itemView);
schemeName = itemView.findViewById(R.id.scheme_name);
amount = itemView.findViewById(R.id.amount);
bank = itemView.findViewById(R.id.bank);
date = itemView.findViewById(R.id.transaction_date);
status = itemView.findViewById(R.id.transaction_status);
}
private void setData(Transaction transaction) {
schemeName.setText(transaction.getSchemeName());
bank.setText(transaction.getBankName());
date.setText(transaction.getTranDate());
int amountValue = Integer.parseInt(transaction.getAmount());
if(amountValue < 0)
amount.setTextColor(getResources().getColor(R.color.color_status_cancelled));
else
amount.setTextColor(getResources().getColor(R.color.color_status_active));
amount.setText(abs(amountValue));
Drawable drawable = status.getCompoundDrawablesRelative()[0];
String st = transaction.getOrderStatus();
if(st.equalsIgnoreCase(TRAN_STATUS_PROCESSED)){
drawable.setTint(getResources().getColor(R.color.color_status_active));
status.setText(TRAN_STATUS_PROCESSED);
} else {
drawable.setTint(getResources().getColor(R.color.color_status_cancelled));
status.setText(TRAN_STATUS_REJECTED);
}
}
}
Tried setting
holder.setIsRecyclable(false);
but that is not an ideal solution I believe.
UPDATE:
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
setContent(getUserTransactions());
And setContent() method:
private void setContent(ArrayList<Transaction> transactions) {
if(adapter == null) {
adapter = new TransactionAdapter(getLayoutInflater(),transactions);
recyclerView.setAdapter(adapter);
} else {
adapter.setTransactionList(transactions);
}
adapter.notifyDataSetChanged();
}

Related

RecyclerView lag on first scroll: Is onCreateViewHolder supposed to be called for every item?

onCreateViewHolder is called every time an item in my list is first displayed and that causes lag the first time the user scrolls.
Is that how it should be? I thought onCreateViewHolder would be called only once per viewType.
Here is my adapter:
public class CompetitionTableAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final CompetitionAdapterOnItemClickHandler mClickHandler;
private List<CompetitionTableItem> mTable;
int calls = 0; //Used to see how many times onCreateViewHolder is called
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
calls++;
if(viewType == CompetitionTableItem.TYPE_HEADER){
View view = LayoutInflater.from(mContext).inflate(R.layout.table_header, viewGroup, false);
Log.i("CompetitionTableAdapter", "onCreateViewHolder "+calls);
return new CompetitionAdapterHeaderViewHolder(view);
}else{
View view = LayoutInflater.from(mContext).inflate(R.layout.table_item, viewGroup, false);
view.setFocusable(true);
Log.i("CompetitionTableAdapter", "onCreateViewHolder "+calls);
return new CompetitionAdapterViewHolder(view);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
int type = getItemViewType(position);
if (type == CompetitionTableItem.TYPE_HEADER) {
HeaderItem header = (HeaderItem) mTable.get(position);
CompetitionAdapterHeaderViewHolder holder = (CompetitionAdapterHeaderViewHolder) viewHolder;
holder.headerTextView.setText(header.getTitle());
} else {
CompetitionAdapterViewHolder holder = (CompetitionAdapterViewHolder) viewHolder;
TeamItem currentTeamTableEntity = (TeamItem)mTable.get(position);
TableEntryEntity tableEntry = currentTeamTableEntity.getTableEntryEntity();
holder.teamNameTextView.setText(tableEntry.getTeam().getName());
holder.pointsTextView.setText(String.valueOf(tableEntry.getPoints()));
holder.positionTextView.setText(String.valueOf(tableEntry.getPosition()));
holder.playedTextView.setText(String.valueOf(tableEntry.getPlayedGames()));
holder.lostTextView.setText(String.valueOf(tableEntry.getLost()));
holder.drawnTextView.setText(String.valueOf(tableEntry.getDraw()));
holder.wonTextView.setText(String.valueOf(tableEntry.getWon()));
String crestUrl = NetworkUtils.getCrestUrl(tableEntry.getTeam().getId(),NetworkUtils.IMAGE_QUALITY_SD);
Picasso.get().load(crestUrl).placeholder(R.drawable.default_crest).error(R.drawable.default_crest).into(holder.crestView);
}
}
#Override
public long getItemId(int position) {
int type = getItemViewType(position);
if (type == CompetitionTableItem.TYPE_HEADER) {
return NO_ID;
}else{
return ((TeamItem)mTable.get(position)).getTableEntryEntity().getTeam().getId();
}
}
public void swapTable(final List<CompetitionTableItem> table) {
mTable = table;
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return mTable.get(position).getType();
}
public interface CompetitionAdapterOnItemClickHandler {
void onItemClick(TableEntryEntity competition);
}
class CompetitionAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final ImageView crestView;
final TextView teamNameTextView;
final TextView positionTextView;
final TextView pointsTextView;
final TextView playedTextView;
final TextView wonTextView;
final TextView drawnTextView;
final TextView lostTextView;
CompetitionAdapterViewHolder(View view) {
super(view);
crestView = view.findViewById(R.id.team_crest);
teamNameTextView = view.findViewById(R.id.team_name);
pointsTextView = view.findViewById(R.id.team_points);
positionTextView = view.findViewById(R.id.team_position);
playedTextView = view.findViewById(R.id.matches_played);
wonTextView = view.findViewById(R.id.matches_won);
drawnTextView = view.findViewById(R.id.matches_drawn);
lostTextView = view.findViewById(R.id.matches_lost);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
TableEntryEntity tableEntryEntity = ((TeamItem)mTable.get(adapterPosition)).getTableEntryEntity();
mClickHandler.onItemClick(tableEntryEntity);
}
}
class CompetitionAdapterHeaderViewHolder extends RecyclerView.ViewHolder {
final TextView headerTextView;
CompetitionAdapterHeaderViewHolder(View view) {
super(view);
headerTextView = view.findViewById(R.id.headerText);
}
}
}
https://github.com/s6joui/football-data-android-java/blob/master/app/src/main/java/tech/joeyck/livefootball/ui/competition_detail/standings/adapter/CompetitionTableAdapter.java
And fragment where RecyclerView is: https://github.com/s6joui/football-data-android-java/blob/master/app/src/main/java/tech/joeyck/livefootball/ui/BaseListFragment.java
Full source code: https://github.com/s6joui/football-data-android-java
I'm using androidx recyclerview version 1.1.0-alpha01

Displaying a single item at the top once, before the looping starts

I am switching all my infinitely long scrollviews into recycler views. This however makes some things a lot harder.
This is my helperclass for the recycler view:
namespace BookOfLife.Screens.Helpers
{
class RecyclerViewHolder : RecyclerView.ViewHolder
{
public ImageView imageView { get; set; }
public TextView txtDescription { get; set; }
public RecyclerViewHolder(View itemView):base(itemView)
{
txtDescription = itemView.FindViewById<TextView>(Resource.Id.RecView_Profile_TaskName);
imageView = itemView.FindViewById<ImageView>(Resource.Id.imageView1);
}
}
class RecyclerViewAdapter : RecyclerView.Adapter
{
private List<DataForProfile> lstData = new List<DataForProfile>();
public RecyclerViewAdapter(List<DataForProfile> lstData)
{
this.lstData = lstData;
}
public override int ItemCount
{
get
{
return lstData.Count;
}
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
RecyclerViewHolder viewHolder = holder as RecyclerViewHolder;
viewHolder.txtDescription.Text = (lstData[position].description);
viewHolder.imageView.SetImageBitmap((lstData[position].img));
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.From(parent.Context);
View itemView = inflater.Inflate(Resource.Layout.RecView_Profile, parent, false);
return new RecyclerViewHolder(itemView);
}
}
public class DataForProfile
{
public int imageId { get; set; }
public Bitmap img { get; set; }
public string description { get; set; }
}
THE PROBLEM:
I also need to display a certain item at the top of the recycler view that only shows up ONCE. Like a header of some sort. I have not been able to figure out how to do that.
This is my code from where I initialize the RC View:
private void initRecView()
{
RecyclerView recycler;
RecyclerViewAdapter adapter;
RecyclerView.LayoutManager layoutManager;
startNumberOfTask = 0;
List<KumulosHelper.Objects.Picture> pictures =
KumulosHelper.Pictures.getNewestXPhotosFromUserInRange
(strUsername, "4", startNumberOfTask.ToString(), "0"); // 4 Bilder werden momentan nur reingeladen!
foreach (var picture in pictures)
{
startNumberOfTask++;
var metrics = Resources.DisplayMetrics;
lstData.Add(new DataForProfile()
{
imageId = startNumberOfTask,
img = (Bitmap.CreateScaledBitmap
(KumulosGeneral.DecodePhotoFromBase64(picture.photo),
metrics.WidthPixels, metrics.WidthPixels, true)),
description = picture.taskId.ToString()
});
}
recycler = FindViewById<RecyclerView>(Resource.Id.recview);
recycler.HasFixedSize = true;
layoutManager = new LinearLayoutManager(this);
recycler.SetLayoutManager(layoutManager);
adapter = new RecyclerViewAdapter(lstData);
recycler.SetAdapter(adapter);
}
In my AXML Layoutfile, I only have a layout for the constantly repeating images that follow.
THanks!

update an item with animation in RecyclerView Adapter

I am using RcyclerView adapter wich holding a chat messages list.
every time a message added to firebase I am using the 'onChildAdded' listener to update the adapter list. I also want to update certain messages by adding their background a changing color-animation.
the problem is I don't know how to access the position of specific messages in my adapter.
this is my chatListadapter:
class ChatListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ChatMessage> msgList;
private static final int VIEW_TYPE_MESSAGE_LEFT = 1;
private static final int VIEW_TYPE_MESSAGE_RIGHT = 2;
private DataReferences DB;
ChatListAdapter(List<ChatMessage> msgList) {
this.msgList = msgList;
}
#Override
public int getItemCount() {
return msgList.size();
}
#Override
public int getItemViewType(int position) {
DB = DataReferences.getInstance();
ChatMessage msg = msgList.get(position);
if (!msg.uid.equals(DB.uid)) {
return VIEW_TYPE_MESSAGE_LEFT;
}
} else
return VIEW_TYPE_MESSAGE_RIGHT;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if (viewType == VIEW_TYPE_MESSAGE_LEFT) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_received, parent, false);
return new LeftViewHolder(view);
} else {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_sent, parent, false);
return new RightViewHolder(view);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int
position) {
ChatMessage msg = msgList.get(position);
if (msg.critic)
switch (holder.getItemViewType()) {
case VIEW_TYPE_MESSAGE_LEFT:
((LeftViewHolder) holder).bind(msg);
break;
case VIEW_TYPE_MESSAGE_RIGHT:
((RightViewHolder) holder).bind(msg);
break;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
private class LeftViewHolder extends RecyclerView.ViewHolder {
TextView messageText, timeText, nameText;
public LeftViewHolder(View itemView) {
super(itemView);
timeText = (TextView) itemView.findViewById(R.id.text_message_time);
nameText = (TextView) itemView.findViewById(R.id.text_message_name);
messageText = (TextView)
itemView.findViewById(R.id.text_message_body);
}
void bind(ChatMessage message) {
messageText.setText(message.getMsg());
timeText.setText(message.getTime());
nameText.setText(message.UserName);
}
}
private class RightViewHolder extends RecyclerView.ViewHolder {
TextView messageText, timeText;
public RightViewHolder(View itemView) {
super(itemView);
timeText = (TextView) itemView.findViewById(R.id.text_message_time);
messageText = (TextView)
itemView.findViewById(R.id.text_message_body);
}
void bind(ChatMessage message) {
messageText.setText(message.getMsg());
timeText.setText(message.getTime());
}
}
}
I suggest you to used FirebaseRecyclerAdapter which come in FirebaseUI library (https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md). It makes handling data in RecyclerView become easier.
To make adapter update specific item. In populateViewHolder of FirebaseRecyclerAdapter you could do something like this (suppose you want to change message background if the message has been read)
override fun populateViewHolder(viewHolder: FieldViewHolder?, model: Message, position: Int) {
if(model.isRead) {
viewholder.updateBackground()
}
}
If you use plain RecyclerView it might need some effort to find specific position and update UI accordingly.
Hope it's help.

Unable to add second child in recyclerview

Unable to add second child in Recyclerview I am passing two different arrays to RecyclerAdapter to display two child layout with different data and views.Is there any solution to add different child layout using same header layout.I added horizontal Recyclerview in vertical Recyclerview and I want to display details like I attached the image
private void setupRecyclerView(RecyclerView recyclerView) {
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter();
int[] images = new int[]{
R.drawable.finance,
R.drawable.business,
R.drawable.financejob,
R.drawable.ecomchallenges
};
ArrayList<ChildView> childViews = new ArrayList<>();
childViews.add(new ChildView(images[0], "The \"Best\" Startup Pitch Deck - How To Raise Venture Capital", "$100"));
childViews.add(new ChildView(images[1], "An Entire MBA in 1 Course:Award Winning Business School Prof", "$100"));
childViews.add(new ChildView(images[2], "What Finance Job is for You? Explanation of 14 Finance Roles", "$100"));
childViews.add(new ChildView(images[3], "Learn To Build Beautiful HTML5 And CSS3 Websites In 1 Month", "$100"));
int[] courseImage = new int[] {
R.drawable.php,
R.drawable.development,
R.drawable.web,
R.drawable.java
};
ArrayList<CourseByType> courseByTypes = new ArrayList<>();
courseByTypes.add(new CourseByType("Technology", courseImage[0]));
courseByTypes.add(new CourseByType("Business", courseImage[1]));
courseByTypes.add(new CourseByType("Photography", courseImage[2]));
courseByTypes.add(new CourseByType("Development", courseImage[3]));
Log.d("","Above adapter");
recyclerAdapter.addItem(new GroupView("Business", childViews));
Log.d("","Below Child");
recyclerAdapter.addCourseByType(new CourseByHeader("Technology", courseByTypes));
Log.d("","Below Course");
recyclerView.setAdapter(recyclerAdapter);
}
This is the main fragment where I set the values to two different
arraylist ArrayList<ChildView> childViews = new ArrayList<>()
and
ArrayList<CourseByType> courseByTypes = new ArrayList<>()
Values of child views are passing properly but CourseByType values are not passing.This is the adapter class for this fragment class.
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
ArrayList<PassValues> containerArrayList;
ArrayList<GroupView> groupViews;
ArrayList<CourseByHeader>courseByHeaders;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.group_title, parent, false);
return new ViewHolder(view);
}
public RecyclerAdapter(){
containerArrayList = new ArrayList<>();
groupViews = new ArrayList<>();
courseByHeaders = new ArrayList<>();
}
public void addContainer(PassValues container){
containerArrayList.add(container);
}
public void addItem(GroupView groupView){
Log.d("","Inside Group method");
groupViews.add(groupView);
}
public void addCourseByType(CourseByHeader courseByHeader){
Log.d("","Inside Course method");
courseByHeaders.add(courseByHeader);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.d("", "Pass Values out of IF" + position);
ChildViewAdapter childViewAdapter = new ChildViewAdapter();
if(position == 0){
GroupView groupView = groupViews.get(position);
holder.title.setText(groupView.getTitle());
Log.d("", "Passing Values" + groupView.getTitle());
holder.recyclerView.setLayoutManager(new LinearLayoutManager(holder.recyclerView.getContext(), LinearLayoutManager.HORIZONTAL, false));
holder.recyclerView.setOnFlingListener(null);
childViewAdapter.addChild(groupView.getChildViewList());
holder.recyclerView.setAdapter(childViewAdapter);
}
if (position == 1) {
CourseByHeader courseByHeader = courseByHeaders.get(position);
holder.title.setText(courseByHeader.getTitle());
Log.d("", "Passing Values" + courseByHeader.getTitle());
holder.recyclerView.setLayoutManager(new LinearLayoutManager(holder.recyclerView.getContext(), LinearLayoutManager.HORIZONTAL, false));
holder.recyclerView.setOnFlingListener(null);
childViewAdapter.addCourse(courseByHeader.getCourseByTypes());
holder.recyclerView.setAdapter(childViewAdapter);
}
}
#Override
public int getItemCount() {
if(getItemViewType(0) == TYPE_HEADER)
return groupViews.size() ;
if (getItemViewType(1) == TYPE_ITEM)
return courseByHeaders.size();
else return -1;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
RecyclerView recyclerView;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.course_title);
recyclerView = (RecyclerView)itemView.findViewById(R.id.group_recycler);
}
}
}
This RecyclerAdapter contains one RecyclerView in that first row has one image and 3 textviews and 2nd row has 1 ImageView and 1 TextView. At position first,one image and 3 textviews are shown but it's not going on 2nd view
This is the view I getting after run on emulator.
This are two child for RecyclerViews
ChildView.java
public class ChildView {
int image;
String course, price;
public ChildView(int image, String course, String price) {
this.image = image;
this.course = course;
this.price = price;
}
public int getImage() {
return image;
}
public String getCourse() {
return course;
}
public String getPrice() {
return price;
}
}
CourseByType.java
public class CourseByType {
String courseName;
int courseImage;
public CourseByType(String courseName, int courseImage) {
this.courseName = courseName;
this.courseImage = courseImage;
}
public String getCourseName() {
return courseName;
}
public int getCourseImage() {
return courseImage;
}
}
CourseByHeader.java
public class CourseByHeader {
String title;
ArrayList<CourseByType> courseByTypes;
public CourseByHeader(String title, ArrayList<CourseByType> courseByTypes) {
this.title = title;
this.courseByTypes = courseByTypes;
}
public String getTitle() {
return title;
}
public ArrayList<CourseByType> getCourseByTypes() {
return courseByTypes;
}
}
GroupView.java
public class GroupView {
String title;
ArrayList<ChildView> childViewList;
String courseBy;
ArrayList<CourseByType> courseByTypes;
public GroupView(String title, ArrayList<ChildView> childViewList) {
this.title = title;
this.childViewList = childViewList;
}
public String getTitle() {
return title;
}
public ArrayList<ChildView> getChildViewList() {
return childViewList;
}
}
Groupview and CouseByType class have title and child list for recycleradapter
ChildViewAdapter.java
public class ChildViewAdapter extends RecyclerView.Adapter {
ArrayList<ChildView> childViewList;
ArrayList<CourseByType> courseByTypes;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
public class ViewHolder extends RecyclerView.ViewHolder{
public ViewHolder(View itemView) {
super(itemView);
}
}
public class GroupHolder extends ViewHolder {
public ImageView iamView;
public TextView course, price;
public GroupHolder(View itemView) {
super(itemView);
iamView = (ImageView) itemView.findViewById(R.id.course_image);
course = (TextView) itemView.findViewById(R.id.course_by);
price = (TextView) itemView.findViewById(R.id.price);
}
}
public void addCourse(ArrayList<CourseByType> courseByType){
courseByTypes = courseByType;
}
public void addChild(ArrayList<ChildView> childView){
childViewList = childView;
}
public class Course extends ViewHolder {
public ImageView courseTypeImage;
public TextView courseType;
public Course(View itemView) {
super(itemView);
courseTypeImage = (ImageView)itemView.findViewById(R.id.course_image);
courseType = (TextView)itemView.findViewById(R.id.course_name_course);
}
}
public ChildViewAdapter() {
childViewList = new ArrayList<>();
courseByTypes = new ArrayList<>();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
RecyclerView.ViewHolder vh = null;
View v;
if(viewType == TYPE_HEADER){
v = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false);
return new GroupHolder(v);
}if(viewType == TYPE_ITEM){
v = LayoutInflater.from(context).inflate(R.layout.type_of_courses, parent, false);
return new Course(v);
}
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof GroupHolder){
Log.d("","instance of Group Holder");
ChildView childView = childViewList.get(position);
((GroupHolder)holder).iamView.setImageResource(childView.getImage());
((GroupHolder)holder).course.setText(childView.getCourse());
((GroupHolder)holder).price.setText(childView.getPrice());
return;
}
if(holder instanceof Course){
Log.d("","instance of Course ");
CourseByType courseByType = courseByTypes.get(position);
((Course)holder).courseTypeImage.setImageResource(courseByType.getCourseImage());
((Course)holder).courseType.setText(courseByType.getCourseName());
return;
}
}
#Override
public int getItemCount() {
int size;
if(childViewList.size()>0){
return size = childViewList.size();
}else return size = courseByTypes.size();
}
#Override
public int getItemViewType(int position) {
if(childViewList.size() != 0 && childViewList.size()>0){
return TYPE_HEADER;
}else return TYPE_ITEM;
}
}
This childview adapter has two view types first is one image and 3 text and second view type contain one image and one text.When I pass values from fragment only first view type get displayed and second view type not gets value from fragment.
To show multiple different views in a recyclerview, you have to override getItemViewType() in the recyclerview adapter.
//getItemViewType enables dynamic viewholder creation
#Override
public int getItemViewType(int position) {
//you will need to add a integer with variable name viewTypeCode
//for view1 set viewTypeCode = 100 and for view2 set viewTypeCode = 200
viewTypeCode = itemList.get(position).getViewTypeCode();
return viewTypeCode;
}
This is how the onCreateViewHolder will be different for multiple viewtypes. You will have to modify yours like this
#Override
public FeedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 100: return new FeedViewHolder(layoutInflater.inflate(R.layout.v1, parent, false),100);
case 200: return new FeedViewHolder(layoutInflater.inflate(R.layout.v2, parent, false),200);
}
return null;
}
OnBindViewHolder will be similarly modified
#Override
public void onBindViewHolder(final FeedViewHolder holder, int position) {
viewTypeCode = itemList.get(position).getViewTypeCode();
switch ( viewTypeCode) {
case 100:
//your code for v1
case 200:
//your code for v2
}
}
Similarly the ViewHolder class is modified
class FeedViewHolder extends RecyclerView.ViewHolder{
//declare variables here
public FeedViewHolder(View v, int viewType) {
super(v);
switch (viewType) {
//instead of itemView.findViewById you will have to use v.findViewById
case 100:
//your code for v1
case 200:
//your code for v2
}
}
For further reference refer to this SO answer
Don't pass two separate list.Make a custom class like this-
class MyClass {
int viewTypeCode;
CustomClass1 c1;
CustomClass2 c2;
//add the setter getter
}
In your activity while preparing the data.
List<MyClass> itemList = new ArrayList<>();
//put whatever logic you need to make the order of the list
//if CustomClass1 object is put then setViewTypeCode(100), setCustomClass2 = null
//if CustomClass2 object is put then setViewTypeCode(200), setCustomClass1 = null
After data is built, then send this to the adapter.

RecyclerView is showing nothing

I have some items in my adapter but nothing is shown in the RecyclerView.
Adapter
public class WorkOrderAdapter extends RecyclerView.Adapter<WorkOrderViewHolder> {
private List<WorkOrder> orders = new LinkedList<>();
public void setData(List<WorkOrder> orders) {
this.orders = orders;
}
#Override
public WorkOrderViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_workorder, parent, false);
return new WorkOrderViewHolder(view);
}
#Override
public void onBindViewHolder(WorkOrderViewHolder holder, int position) {
WorkOrder order = orders.get(position);
holder.bind(order);
}
#Override
public int getItemCount() {
return orders.size();
}
}
ViewHolder
public class WorkOrderViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private TextView description;
private TextView date;
public WorkOrderViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title_textview);
description = (TextView) view.findViewById(R.id.description_textview);
date = (TextView) view.findViewById(R.id.date_textview);
}
public void bind(WorkOrder order) {
title.setText("Test");
description.setText("Test");
date.setText("Test");
}
}
Activity (Using AndroidAnnotations)
#EActivity(R.layout.activity_workorders)
#OptionsMenu(R.menu.activity_workorders)
public class WorkOrdersActivity extends ToolbarActivity {
#ViewById(R.id.orders_recyclerview)
RecyclerView ordersList;
List<WorkOrder> orders = new LinkedList<>();
private WorkOrderAdapter adapter;
{
adapter = new WorkOrderAdapter();
orders.add(new WorkOrder());
orders.add(new WorkOrder());
orders.add(new WorkOrder());
adapter.setData(orders);
}
#AfterViews
public void initViews() {
ordersList.setAdapter(adapter);
}
}
Please add the LayoutManager to the RecyclerView and try again
ordersList.setLayoutManager(new LinearLayoutManager(this));
ordersList.setAdapter(adapter);

Categories

Resources