RecyclerView in RecyclerView parent.notifyDataSetChanged loose position of child RecyclerView - android

I develop a fragment using Horizontal RecyclerView in a Vertical RecyclerView (like Google Play Store).
When i notifyDataSetChanged from the parent RecyclerView, the child RecyclerView lose the position because the setAdapter is call in the onBindViewHolder I think. Also when i scroll to the 5th position in the first horizontal recyclerview if i scroll down and come back up i loose the 5th position.
I try to use RecyclerView.scrollToPosition() but that don't work.
So i think i have two solution :
a way (by a method or setting) to keep the position of my child recycler view. (BEST SOLUTION)
a way to set manually the recyclerview position to where it was before the refresh. (ELSE SOLUTION)
Here my Parent Adapter :
public class ProfilesCardViewListAdapter extends RecyclerView.Adapter<ProfilesCardViewListAdapter.ItemRowHolder> {
private ArrayList<AidodysProfile> sectionsList;
private Context context;
private boolean[] isShown;
private ProfileCardViewItemAdapter itemAdapters[];
public ProfilesCardViewListAdapter(ArrayList<AidodysProfile> sectionsList, Context context) {
this.sectionsList = sectionsList;
this.context = context;
this.isShown = new boolean[sectionsList.size()];
this.itemAdapters = new ProfileCardViewItemAdapter[sectionsList.size()];
for (int i = 0; i < sectionsList.size(); i++) {
this.isShown[i] = true;
this.itemAdapters[i] = new ProfileCardViewItemAdapter(sectionsList.get(i).getProfiles(), context, this);
}
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_card_view_horizontal, null);
final ItemRowHolder rowHolder = new ItemRowHolder(view);
return rowHolder;
}
#Override
public void onBindViewHolder(final ItemRowHolder holder, final int position) {
String sectionName = sectionsList.get(position).getName();
AidodysProfile[] sectionItems = sectionsList.get(position).getProfiles();
holder.sectionTitle.setTextSize(context.getResources().getDimension(R.dimen.text_size_profileslist_section_title));
holder.sectionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showHideSection(holder, position);
}
});
if (isShown[position]) {
holder.itemRecyclerView.setVisibility(View.VISIBLE);
holder.sectionButton.setText(context.getString(R.string.action_profiles_section_hide));
} else {
holder.itemRecyclerView.setVisibility(View.GONE);
holder.sectionButton.setText(context.getText(R.string.action_profiles_section_show));
}
if (!sectionsList.get(position).isLeaf()) { // FOLDER
if (sectionName.equals("")) {
holder.sectionTitle.setVisibility(View.GONE);
holder.sectionButton.setVisibility(View.GONE);
} else {
holder.sectionTitle.setVisibility(View.VISIBLE);
holder.sectionButton.setVisibility(View.VISIBLE);
}
holder.sectionTitle.setText(sectionName);
} else { // PROFILE
return;
}
holder.itemRecyclerView.setHasFixedSize(true);
holder.itemRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
holder.itemRecyclerView.setAdapter(itemAdapters[position]);
}
private void showHideSection(ItemRowHolder holder, int position) {
if (holder.itemRecyclerView.getVisibility() == View.VISIBLE) {
isShown[position] = false;
holder.itemRecyclerView.setVisibility(View.GONE);
holder.sectionButton.setText(context.getText(R.string.action_profiles_section_show));
} else {
isShown[position] = true;
holder.itemRecyclerView.setVisibility(View.VISIBLE);
holder.sectionButton.setText(context.getString(R.string.action_profiles_section_hide));
}
}
#Override
public int getItemCount() {
return (sectionsList != null ? sectionsList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView sectionTitle;
protected RecyclerView itemRecyclerView;
protected Button sectionButton;
public ItemRowHolder(View view) {
super(view);
this.sectionTitle = (TextView) view.findViewById(R.id.section_title);
this.itemRecyclerView = (RecyclerView) view.findViewById(R.id.item_recycler_view);
this.sectionButton = (Button) view.findViewById(R.id.section_button);
}
}
}
Child Adapter :
class ProfileCardViewItemAdapter extends RecyclerView.Adapter<ProfileCardViewItemAdapter.SingleItemRowHolder> {
private AidodysProfile[] itemsList;
private CurrentUser currentUser;
private Context context;
private int selectedPos = -1;
private ProfilesCardViewListAdapter parent;
public ProfileCardViewItemAdapter(AidodysProfile[] itemsList, Context context, ProfilesCardViewListAdapter parent) {
this.itemsList = itemsList;
this.context = context;
this.parent = parent;
this.currentUser = CurrentUser.getInstance(context);
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_card_view_horizontal, null);
SingleItemRowHolder rowHolder = new SingleItemRowHolder(view);
return (rowHolder);
}
#Override
public void onBindViewHolder(final SingleItemRowHolder holder, final int position) {
AidodysProfile profile = itemsList[position];
holder.itemCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectProfile(holder, position);
}
});
if (profile.equals(currentUser.getProfile())) {
selectedPos = position;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.itemCardView.setCardBackgroundColor(context.getColor(R.color.aidodysRed));
} else {
holder.itemCardView.setCardBackgroundColor(context.getResources().getColor(R.color.aidodysRed));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.itemCardView.setCardBackgroundColor(context.getColor(R.color.white));
} else {
holder.itemCardView.setCardBackgroundColor(context.getResources().getColor(R.color.white));
}
}
holder.itemTitle.setText(profile.getName());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.itemPicture.setImageDrawable(context.getDrawable(R.drawable.ic_sheet_smile_black_48dp));
holder.button1.setImageDrawable(context.getDrawable(R.drawable.ic_edit_black_24dp));
holder.button2.setImageDrawable(context.getDrawable(R.drawable.ic_look_profile));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.itemTitle.setTextAppearance(R.style.Aidodys_Text_ProfilesList_Item);
holder.itemPicture.setColorFilter(context.getColor(R.color.white));
holder.topParts.setBackgroundColor(context.getColor(R.color.aidodysRed));
} else {
holder.itemTitle.setTextColor(context.getResources().getColor(R.color.white));
holder.itemTitle.setTextSize(context.getResources().getDimension(R.dimen.text_size_profileslist_item));
holder.itemPicture.setColorFilter(context.getResources().getColor(R.color.white));
holder.topParts.setBackgroundColor(context.getResources().getColor(R.color.aidodysRed));
}
} else {
holder.button1.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_edit_black_24dp));
holder.button2.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_look_profile));
holder.itemTitle.setTextColor(context.getResources().getColor(R.color.white));
holder.itemTitle.setTextSize(context.getResources().getDimension(R.dimen.text_size_profileslist_item));
holder.itemPicture.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_sheet_smile_black_48dp));
holder.itemPicture.setColorFilter(context.getResources().getColor(R.color.white));
holder.topParts.setBackgroundColor(context.getResources().getColor(R.color.aidodysRed));
}
}
private void selectProfile(SingleItemRowHolder holder, int position) {
SharedPreferences.Editor editor = context.getSharedPreferences("Aidodys", 0).edit();
editor.putString("profile", new Gson().toJson(itemsList[position]));
editor.apply();
currentUser.setProfile(itemsList[position]);
parent.notifyDataSetChanged();
notifyDataSetChanged();
((RecyclerView)holder.itemCardView.getParent()).scrollToPosition(position);
selectedPos = position;
}
#Override
public int getItemCount() {
return (itemsList != null ? itemsList.length : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected TextView itemTitle;
protected ImageView itemPicture;
protected CardView itemCardView;
protected ImageView button1;
protected ImageView button2;
protected LinearLayout topParts;
public SingleItemRowHolder(View view) {
super(view);
this.itemTitle = (TextView)view.findViewById(R.id.item_title);
this.itemPicture = (ImageView)view.findViewById(R.id.item_picture);
this.itemCardView = (CardView)view.findViewById(R.id.card_view_list_item);
this.topParts = (LinearLayout)view.findViewById(R.id.card_view_list_item_top_part);
this.button1 = (ImageView)view.findViewById(R.id.item_button_1);
this.button2 = (ImageView)view.findViewById(R.id.item_button_2);
}
}
}
If someone has a solution for me
Thank you

Store x scroll offset in a SparseArray for position and restore when bind view holder.
public class ProfilesCardViewListAdapter extends RecyclerView.Adapter<ProfilesCardViewListAdapter.ItemRowHolder> {
private SparseIntArray sparseArray = new SparseIntArray();
#Override
public void onBindViewHolder(final ItemRowHolder holder, final int position) {
// Use srollBy for animate scrolling
holder.itemRecyclerView.srollBy(sparseArray.get(position, 0), 0);
// Or scrollTo for restore previous x offset
//holder.itemRecyclerView.srollTo(sparseArray.get(position, 0), 0);
holder.itemRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
sparseArray.put(position, dx);
}
}
}
}

I found a solution, i use the onTouchListener in the child recyclerView to set a scrollPosition (i don't use onScrollListener because this method is deprecated) i implement a getter to this field to get the scroll position from the parent RecyclerView and so at the end of the onBindViewHolder in the parent RecyclerView i call (child)RecyclerView.scrollToPosition(scrollPosition).
And that's make the job
Parent RecyclerViewAdapter :
public class ProfilesCardViewListAdapter extends RecyclerView.Adapter<ProfilesCardViewListAdapter.ItemRowHolder> {
private ArrayList<AidodysProfile> sectionsList;
private Context context;
private boolean[] isShown;
private ProfileCardViewItemAdapter itemAdapters[];
public ProfilesCardViewListAdapter(ArrayList<AidodysProfile> sectionsList, Context context) {
this.sectionsList = sectionsList;
this.context = context;
this.isShown = new boolean[sectionsList.size()];
this.itemAdapters = new ProfileCardViewItemAdapter[sectionsList.size()];
for (int i = 0; i < sectionsList.size(); i++) {
this.isShown[i] = true;
this.itemAdapters[i] = new ProfileCardViewItemAdapter(sectionsList.get(i).getProfiles(), context, this);
}
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_card_view_horizontal, null);
final ItemRowHolder rowHolder = new ItemRowHolder(view);
rowHolder.itemRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
return rowHolder;
}
#Override
public void onBindViewHolder(final ItemRowHolder holder, final int position) {
String sectionName = sectionsList.get(position).getName();
AidodysProfile[] sectionItems = sectionsList.get(position).getProfiles();
holder.sectionTitle.setTextSize(context.getResources().getDimension(R.dimen.text_size_profileslist_section_title));
holder.sectionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showHideSection(holder, position);
}
});
if (isShown[position]) {
holder.itemRecyclerView.setVisibility(View.VISIBLE);
holder.sectionButton.setText(context.getString(R.string.action_profiles_section_hide));
} else {
holder.itemRecyclerView.setVisibility(View.GONE);
holder.sectionButton.setText(context.getText(R.string.action_profiles_section_show));
}
if (!sectionsList.get(position).isLeaf()) { // FOLDER
if (sectionName.equals("")) {
holder.sectionTitle.setVisibility(View.GONE);
holder.sectionButton.setVisibility(View.GONE);
} else {
holder.sectionTitle.setVisibility(View.VISIBLE);
holder.sectionButton.setVisibility(View.VISIBLE);
}
holder.sectionTitle.setText(sectionName);
} else { // PROFILE
return;
}
holder.itemRecyclerView.setHasFixedSize(true);
holder.itemRecyclerView.setAdapter(itemAdapters[position]);
holder.itemRecyclerView.scrollToPosition(itemAdapters[position].getScrollPos());
}
private void showHideSection(ItemRowHolder holder, int position) {
if (holder.itemRecyclerView.getVisibility() == View.VISIBLE) {
isShown[position] = false;
holder.itemRecyclerView.setVisibility(View.GONE);
holder.sectionButton.setText(context.getText(R.string.action_profiles_section_show));
} else {
isShown[position] = true;
holder.itemRecyclerView.setVisibility(View.VISIBLE);
holder.sectionButton.setText(context.getString(R.string.action_profiles_section_hide));
}
}
#Override
public int getItemCount() {
return (sectionsList != null ? sectionsList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView sectionTitle;
protected RecyclerView itemRecyclerView;
protected Button sectionButton;
public ItemRowHolder(View view) {
super(view);
this.sectionTitle = (TextView) view.findViewById(R.id.section_title);
this.itemRecyclerView = (RecyclerView) view.findViewById(R.id.item_recycler_view);
this.sectionButton = (Button) view.findViewById(R.id.section_button);
}
}
}
Child RecyclerViewAdapter :
class ProfileCardViewItemAdapter extends RecyclerView.Adapter<ProfileCardViewItemAdapter.SingleItemRowHolder> {
private AidodysProfile[] itemsList;
private CurrentUser currentUser;
private Context context;
private int scrollPos = 0;
private ProfilesCardViewListAdapter parent;
public int getScrollPos() {
return scrollPos;
}
public ProfileCardViewItemAdapter(AidodysProfile[] itemsList, Context context, ProfilesCardViewListAdapter parent) {
this.itemsList = itemsList;
this.context = context;
this.parent = parent;
this.currentUser = CurrentUser.getInstance(context);
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_card_view_horizontal, null);
SingleItemRowHolder rowHolder = new SingleItemRowHolder(view);
return (rowHolder);
}
#Override
public void onBindViewHolder(final SingleItemRowHolder holder, final int position) {
AidodysProfile profile = itemsList[position];
holder.itemCardView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
scrollPos = position;
return false;
}
});
holder.itemCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectProfile(holder, position);
}
});
if (profile.getId() == currentUser.getProfile().getId()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.itemCardView.setCardBackgroundColor(context.getColor(R.color.aidodysRed));
} else {
holder.itemCardView.setCardBackgroundColor(context.getResources().getColor(R.color.aidodysRed));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.itemCardView.setCardBackgroundColor(context.getColor(R.color.white));
} else {
holder.itemCardView.setCardBackgroundColor(context.getResources().getColor(R.color.white));
}
}
holder.itemTitle.setText(profile.getName());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.itemPicture.setImageDrawable(context.getDrawable(R.drawable.ic_sheet_smile_black_48dp));
holder.button1.setImageDrawable(context.getDrawable(R.drawable.ic_edit_black_24dp));
holder.button2.setImageDrawable(context.getDrawable(R.drawable.ic_look_profile));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.itemTitle.setTextAppearance(R.style.Aidodys_Text_ProfilesList_Item);
holder.itemPicture.setColorFilter(context.getColor(R.color.white));
holder.topParts.setBackgroundColor(context.getColor(R.color.aidodysRed));
} else {
holder.itemTitle.setTextColor(context.getResources().getColor(R.color.white));
holder.itemTitle.setTextSize(context.getResources().getDimension(R.dimen.text_size_profileslist_item));
holder.itemPicture.setColorFilter(context.getResources().getColor(R.color.white));
holder.topParts.setBackgroundColor(context.getResources().getColor(R.color.aidodysRed));
}
} else {
holder.button1.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_edit_black_24dp));
holder.button2.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_look_profile));
holder.itemTitle.setTextColor(context.getResources().getColor(R.color.white));
holder.itemTitle.setTextSize(context.getResources().getDimension(R.dimen.text_size_profileslist_item));
holder.itemPicture.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_sheet_smile_black_48dp));
holder.itemPicture.setColorFilter(context.getResources().getColor(R.color.white));
holder.topParts.setBackgroundColor(context.getResources().getColor(R.color.aidodysRed));
}
}
private void selectProfile(SingleItemRowHolder holder, int position) {
SharedPreferences.Editor editor = context.getSharedPreferences("Aidodys", 0).edit();
editor.putString("profile", new Gson().toJson(itemsList[position]));
editor.apply();
currentUser.setProfile(itemsList[position]);
parent.notifyDataSetChanged();
}
#Override
public int getItemCount() {
return (itemsList != null ? itemsList.length : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected TextView itemTitle;
protected ImageView itemPicture;
protected CardView itemCardView;
protected ImageView button1;
protected ImageView button2;
protected LinearLayout topParts;
public SingleItemRowHolder(View view) {
super(view);
this.itemTitle = (TextView)view.findViewById(R.id.item_title);
this.itemPicture = (ImageView)view.findViewById(R.id.item_picture);
this.itemCardView = (CardView)view.findViewById(R.id.card_view_list_item);
this.topParts = (LinearLayout)view.findViewById(R.id.card_view_list_item_top_part);
this.button1 = (ImageView)view.findViewById(R.id.item_button_1);
this.button2 = (ImageView)view.findViewById(R.id.item_button_2);
}
}
}

Related

how to remove all items from RecyclerView on toolbar icon delete in android

Hello friend a lot of search but not working plz help me.
my probem is delete all history from adaptor using on toolbar delete icon how to remove adaptor data
below code first show adaptor and mainactivity
public void removehistory(View view)
button click to remove items from adaptor how to solve this problem sorry for bad english and advance thanks
HistoryAdaptor
public class HistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Object> data;
private GenCallback<HistoryModel> clickListener;
private static final int NATIVE_AD = 1;
private static final int HISTORY_ITEM = 2;
private LayoutInflater inflater;
// private Button removedata;
public HistoryAdapter() {
this.data = new ArrayList<>();
inflater = (LayoutInflater) App.getInstance().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case NATIVE_AD:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ad_unified, null, false);
return new NativeAdHolder(view);
case HISTORY_ITEM:
default:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false);
return new ViewHolder(view);
}
// return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false));
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case NATIVE_AD:
((NativeAdHolder) holder).bind((UnifiedNativeAd) data.get(position));
break;
case HISTORY_ITEM:
default:
((ViewHolder) holder).bind((HistoryModel) data.get(position));
break;
}
}
#Override
public int getItemViewType(int position) {
if (data.get(position) instanceof UnifiedNativeAd) {
return NATIVE_AD;
} else {
return HISTORY_ITEM;
}
}
#Override
public int getItemCount() {
return data.size();
}
public void addItem(Object obj, int pos) {
this.data.add(pos, obj);
notifyItemInserted(pos);
}
public void updateData(ArrayList<HistoryModel> list) {
this.data.clear();
this.data.addAll(list);
notifyDataSetChanged();
}
public void clear() {
if (this.data != null && this.data.size() != 0) {
this.data.clear();
notifyDataSetChanged();
}
}
public void setClickListener(GenCallback<HistoryModel> clickListener) {
this.clickListener = clickListener;
}
public void showStarredOnly() {
/*Iterator<Object> iterator = data.iterator();
int pos = 0;
while (iterator.hasNext()) {
if (iterator.next() instanceof HistoryModel) {
HistoryModel historyModel = (HistoryModel) iterator.next();
if (!historyModel.isStarred()) {
iterator.remove();
// notifyItemRemoved(pos);
}
}
pos++;
}
notifyDataSetChanged();*/
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.tvFromLang)
TextView tvFromLang;
#BindView(R.id.tvFromText)
TextView tvFromText;
#BindView(R.id.tvToLang)
TextView tvToLang;
#BindView(R.id.tvToText)
TextView tvToText;
#BindView(R.id.ivStar)
ImageView ivStar;
#BindView(R.id.llMain)
CardView llMain;
#BindView(R.id.tvDate)
TextView tvDate;
public ViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
llMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clickListener != null) {
clickListener.onCallback((HistoryModel) data.get(getAdapterPosition()));
}
}
});
llMain.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int pos = getAdapterPosition();
HistoryModel historyModel = (HistoryModel) data.get(pos);
boolean isStar = historyModel.isStarred();
String from = historyModel.getFromLang();
String to = historyModel.getToLang();
Dialogs.INSTANCE.showActionsDialog(llMain.getContext(), isStar, from, to, new HistoryActionCallback() {
#Override
public void onClickCopyFrom() {
Utils.copyText(historyModel.getFromText());
Logger.logFabric(Constants.Events.COPY_FROM);
}
#Override
public void onClickCopyTo() {
Utils.copyText(historyModel.getToText());
Logger.logFabric(Constants.Events.COPY_TO);
}
#Override
public void onClickStar() {
Logger.logFabric(Constants.Events.MARKED_AS_FAV);
historyModel.setStarred(!isStar);
notifyItemChanged(pos);
RoomRepository.getNew().updateHistoryItem(historyModel);
// notifyDataSetChanged();
}
#Override
public void onClickDelete() {
String message = "Are you sure you want to delete?";
Dialogs.INSTANCE.showConfirmationDialog(view.getContext(), message, new View.OnClickListener() {
#Override
public void onClick(View view) {
RoomRepository.getNew().deleteHistoryRecord(historyModel.getTimeStamp());
data.remove(pos);
notifyItemRemoved(pos);
Dialogs.INSTANCE.dismissDialog();
Logger.logFabric(Constants.Events.ITEM_DELETED);
}
});
}
});
return false;
}
});
}
public void bind(HistoryModel item) {
StringBuilder builder = new StringBuilder();
builder.append(item.getFromLang()).append("(").append(item.getFromCode()).append(")");
tvFromLang.setText(builder);
tvFromText.setText(item.getFromText());
builder.setLength(0);
builder.append(item.getToLang()).append("(").append(item.getToCode()).append(")");
tvToLang.setText(builder);
tvToText.setText(item.getToText());
String date = Utils.formatDate(item.getTimeStamp(), "EEE, MMM d, yyyy");
tvDate.setText(date);
ivStar.setVisibility(item.isStarred() ? View.VISIBLE : View.GONE);
}
MainActivity
public class HistoryActivity extends AppCompatActivity {
private HistoryAdapter mAdapter;
private ArrayList<Object> data;
private Activity mCurrentActivity;
private RecyclerView rvHistory;
private Button clearh;
private GenCallback<HistoryModel> clickListener;
private ArrayList<HistoryModel> datamodel = new ArrayList<>();
private ArrayList<String> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
rvHistory = findViewById(R.id.rvHistory);
ImageView imgb = findViewById(R.id.imgback);
initAdapter();
getAdapter();
imgb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HistoryActivity.super.onBackPressed();
}
});
}
private void getAdapter() {
RoomRepository.getNew().getAllHistory(mCallback);
}
private void initAdapter() {
mAdapter = new HistoryAdapter();
LinearLayoutManager layoutManager = new LinearLayoutManager(mCurrentActivity);
rvHistory.setLayoutManager(layoutManager);
rvHistory.setAdapter(mAdapter);
}
private IRoomDataHandler mCallback = new RoomDataHandler() {
#Override
public void onGetAllHistory(ArrayList<HistoryModel> list) {
// if (isSafe()) {
mAdapter.updateData(list);
// showLoader(false);
// checkForNoData();
// if (AdUtils.getInstance().getNativeAd() != null) {
//
// }
}
#Override
public void onError(String error) {
// showLoader(false);
// checkForNoData();
}
};
public void removehistory(View view) {
//problem is here
mAdapter.notifyItemRemoved(i);
}
}
call clear() method from on click oh that button like this.
public void removehistory(View view) {
//problem is here
mAdapter.clear()
}

Hide the visibility of the nested recyclerview in android on ChildItem Click

I have a nested recycler view on which child item click I want the whole child recycler view to set visibility GONE.
I have tried some way to do it. But keeps on loosing the recycler view state and wrong data show's up. Help, please.
Here is ParentAdapter.java code
public class MessageListAdapter extends RecyclerView.Adapter {
private Context mContext;
private static final int VIEW_TYPE_MESSAGE_SENT = 1;
private static final int VIEW_TYPE_MESSAGE_RECEIVED = 2;
private List<Payload> chatMessageList;
private RecyclerView.RecycledViewPool recycledViewPool;
private OnItemClickListener onItemClickListener;
MessageListAdapter(Context context, List<Payload> chatMessageList, OnItemClickListener onItemClickListener) {
this.mContext = context;
this.chatMessageList = chatMessageList;
this.onItemClickListener = onItemClickListener;
recycledViewPool = new RecyclerView.RecycledViewPool();
}
#Override
public int getItemCount() {
return chatMessageList.size();
}
// Determines the appropriate ViewType according to the sender of the message.
#Override
public int getItemViewType(int position) {
Payload message = chatMessageList.get(position);
if (TextUtils.equals(message.getUserType(), "USER")) {
// If the current user is the sender of the message
return VIEW_TYPE_MESSAGE_SENT;
} else {
// If some other user sent the message
return VIEW_TYPE_MESSAGE_RECEIVED;
}
}
// Inflates the appropriate layout according to the ViewType.
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
if (viewType == VIEW_TYPE_MESSAGE_SENT) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_user_msg, parent, false);
return new SentMessageHolder(view);
} else {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_bot_msg, parent, false);
return new ReceivedMessageHolder(view);
}
}
// Passes the message object to a ViewHolder so that the contents can be bound to UI.
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Payload chatMessage = chatMessageList.get(position);
switch (holder.getItemViewType()) {
case VIEW_TYPE_MESSAGE_SENT:
((SentMessageHolder) holder).bind(chatMessage.getMessage(), getFormattedTime());
break;
case VIEW_TYPE_MESSAGE_RECEIVED:
((ReceivedMessageHolder) holder).bind(chatMessage.getMessage(), getFormattedTime());
((ReceivedMessageHolder) holder).bindRv(chatMessage, mContext, recycledViewPool, onItemClickListener);
break;
}
}
private static class SentMessageHolder extends RecyclerView.ViewHolder {
TextView txtViewChatMsgUser;
TextView txtViewDateTimeUser;
SentMessageHolder(View itemView) {
super(itemView);
txtViewChatMsgUser = itemView.findViewById(R.id.txtViewChatMsgUser);
txtViewDateTimeUser = itemView.findViewById(R.id.txtViewDateTimeUser);
}
void bind(String message, String time) {
txtViewChatMsgUser.setText(message);
txtViewDateTimeUser.setText(time);
}
}
private class ReceivedMessageHolder extends RecyclerView.ViewHolder {
TextView txtViewChatMsgBot;
RecyclerView rvDeepLink;
TextView txtViewDateTimeBot;
ReceivedMessageHolder(View itemView) {
super(itemView);
txtViewChatMsgBot = itemView.findViewById(R.id.txtViewChatMsgBot);
rvDeepLink = itemView.findViewById(R.id.itemRvDeepLink);
txtViewDateTimeBot = itemView.findViewById(R.id.txtViewDateTimeBot);
}
void bind(String message, String time) {
txtViewChatMsgBot.setText(message);
txtViewDateTimeBot.setText(time);
}
void bindRv(Payload chatMessage, Context context, RecyclerView.RecycledViewPool recycledViewPool, OnItemClickListener onItemClickListener) {
if (chatMessage.getData() != null && !chatMessage.isOptionSelected()) {
DeepLinkAdapter deepLinkAdapter = new DeepLinkAdapter(context, chatMessage.getData(), onItemClickListener, getAdapterPosition());
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
rvDeepLink.setLayoutManager(linearLayoutManager);
rvDeepLink.setAdapter(deepLinkAdapter);
rvDeepLink.setRecycledViewPool(recycledViewPool);
deepLinkAdapter.notifyDataSetChanged();
} else {
rvDeepLink.setVisibility(View.GONE);
}
}
}
private String getFormattedTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm aa", Locale.ENGLISH);
return dateFormat.format(new Date());
}
public void clearData() {
chatMessageList.clear();
notifyDataSetChanged();
}
public void onSelected(int position) {
chatMessageList.get(position).setOptionSelected(true);
notifyItemChanged(position);
}
}
Here is my ChildAdapter.java code:
public class DeepLinkAdapter extends RecyclerView.Adapter<DeepLinkAdapter.DeepLinkViewHolder> {
private List<DataItem> dataItemList;
private Context context;
private OnItemClickListener onItemClickListener;
private int parentPos;
DeepLinkAdapter(Context context, List<DataItem> dataItemList, OnItemClickListener onItemClickListener, int parentPos) {
this.context = context;
this.dataItemList = dataItemList;
this.onItemClickListener = onItemClickListener;
this.parentPos = parentPos;
}
#NonNull
#Override
public DeepLinkViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new DeepLinkViewHolder(LayoutInflater.from(context).inflate(R.layout.inner_bot_msg, parent, false), onItemClickListener, parentPos);
}
#Override
public void onBindViewHolder(#NonNull final DeepLinkViewHolder holder, final int position) {
DataItem dataItem = dataItemList.get(position);
if (TextUtils.isEmpty(dataItem.getDeeplink())) {
holder.deepLinkText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
} else {
holder.deepLinkText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_right_arrow, 0);
}
if (!TextUtils.isEmpty(dataItem.getText())) {
holder.deepLinkText.setVisibility(View.VISIBLE);
holder.deepLinkText.setText(dataItem.getText());
} else {
holder.deepLinkText.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
if (dataItemList != null) {
return dataItemList.size();
} else {
return 0;
}
}
class DeepLinkViewHolder extends RecyclerView.ViewHolder {
private TextView deepLinkText;
DeepLinkViewHolder(View itemView, OnItemClickListener onItemClickListener, int parentPos) {
super(itemView);
deepLinkText = itemView.findViewById(R.id.innerDeepLinkMsgText);
if (onItemClickListener != null) {
deepLinkText.setOnClickListener(v -> {
onItemClickListener.onItemClick(getAdapterPosition(), parentPos);
});
}
}
}
}
Here is my Click Listener Code in the Activity:
#Override
public void onItemClick(int childPos, int parentPos) {
if (TextUtils.isEmpty(chatMessageList.get(parentPos).getData().get(childPos).getDeeplink())) {
String message = chatMessageList.get(parentPos).getData().get(childPos).getText();
if (!viewModel.sendMessage(message)) {
setMessage(getString(R.string.error_something_went_wrong), ChatBotManager.UserType.BOT.toString());
} else {
messageListAdapter.onSelected(parentPos);
setMessage(message, ChatBotManager.UserType.USER.toString());
}
} else {
if (TextUtils.equals(chatMessageList.get(parentPos).getData().get(childPos).getDeeplink(), "restart")) {
if (messageListAdapter != null) {
messageListAdapter.clearData();
viewModel.sendMessage("start");
}
} else {
String uri = chatMessageList.get(parentPos).getData().get(childPos).getDeeplink();
Intent newIntent = new Intent(ApplicationClass.getContext(), TalkLinkingActivity.class);
newIntent.setData(Uri.parse(uri));
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);
finish();
}
}
}
Please help what I am missing here, My goal is to have a click listener from the child adapter on Activity, and also after the click on the item, I want to remove the whole recycler view. Just like a chatbot in Swiggy.
Have a method in DeepLinkAdapter that clears the whole list:
public class DeepLinkAdapter extends RecyclerView.Adapter<DeepLinkAdapter.DeepLinkViewHolder> {
.......
public void clearTheWholeList(){
dataItemList.clear();
notifyDataSetChanged();
}
}
Have a method in your MessageListAdapter that removes an item completely:
public class MessageListAdapter extends RecyclerView.Adapter {
......
......
private int positionToClear = -1;
public void removeItem(int position){
positionToClear = position;
notifyDataSetChanged();
}
//in onBindViewHolder
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
............
............
//pass the positionToClear here
((ReceivedMessageHolder) holder).bindRv(chatMessage, mContext, recycledViewPool, onItemClickListener , positionToClear);
}
.......
}
In ReceivedMessageHolder
private class ReceivedMessageHolder extends RecyclerView.ViewHolder {
//here add new param for removed position
void bindRv(Payload chatMessage, Context context, RecyclerView.RecycledViewPool recycledViewPool, OnItemClickListener onItemClickListener, int positionToClear) {
if (chatMessage.getData() != null && !chatMessage.isOptionSelected()) {
DeepLinkAdapter deepLinkAdapter = new DeepLinkAdapter(context, chatMessage.getData(), onItemClickListener, getAdapterPosition());
//do a check here
if(getAdapterPosition() == positionToClear){
deepLinkAdapter.clearTheWholeList();
}
.......
.......
.......
} else {
rvDeepLink.setVisibility(View.GONE);
}
}
}
Assuming the onItemClick interface is working:
#Override
public void onItemClick(int childPos, int parentPos) {
...........
...........
//somewhere where you want the item to be removed
messageListAdapter.removeItem(parentPos);
............
............
}

How to expand the RecyclerView items?

I have alot of ImageViews in RecyclerView item in LinearLayout. When I scroll horizontally it scrolls perfectly. But I want the focused item in RecyclerView to get expanded from the actual size.
Any help ?
public class NavigationBarManager extends RecyclerView.Adapter<NavigationBarManager.FilterItemHolder> implements OnItemSelectedListener, AnimatorListener{//, Observer {
private static final String TAG = "NavigationBarManager";
private RecyclerView mRecyclerView ;
private int mSelectedItem = 0;
private NotificationHandler mAnimNtfHandler;
public static final int DIRECTION_LEFT = -1;
public static final int DIRECTION_RIGHT = 1;
Context mContext;
FilterItemHolder mFilterItemHolder;
private ArrayList<String> mFilterStringList;
private ArrayList<Drawable> mFilterDrawableList;
private ArrayList<Integer> mCursorIdxList;
private ArrayList<Integer> mFilterIdList;
private HtvChannelListUtil mListUtil;
private ITvSettingsManager mSettings;
private RecyclerView.SmoothScroller smoothScroller;
private LinearLayoutManager mRecyclerViewMgr = null;
public NavigationBarManager(Context context)
{
mContext = context;
mAnimNtfHandler = NotificationHandler.getInstance();
mFilterStringList = new ArrayList<String>();
mFilterDrawableList = new ArrayList<Drawable>();
mFilterIdList = new ArrayList<Integer>();
mCursorIdxList = new ArrayList<Integer>();
mListUtil = HtvChannelListUtil.getInstance();
mSettings = ITvSettingsManager.Instance.getInterface();
mCacheManager = HtvChannelCacheManager.getInstance();
mFillDataIntoNavigationBar();
mNtfHandler = NotificationHandler.getInstance();
}
public void setLayoutManager(LinearLayoutManager pRecyclerViewMgr)
{
mRecyclerViewMgr = pRecyclerViewMgr;
}
public class FilterItemHolder extends RecyclerView.ViewHolder
{
ImageView imageView;
//ImageView mBgView;
public FilterItemHolder(View itemView)
{
super(itemView);
// get the reference of item view's
imageView=(ImageView) itemView.findViewById(R.id.imageview);
//mBgView = (ImageView) itemView.findViewById(R.id.bgView);
}
}
#Override
public FilterItemHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
Log.e(TAG,"onCreateViewHolder viewType" +viewType);
View lViewHolder = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
FilterItemHolder lHolder = new FilterItemHolder(lViewHolder);
mFilterItemHolder = lHolder;
return lHolder;
}
#Override
public void onBindViewHolder(FilterItemHolder holder, final int position)
{
Log.e(TAG,"onBindViewHolder position=" +position);
Log.e(TAG,"onBindViewHolder getAdapterPosition=" +holder.getAdapterPosition());
Log.e(TAG,"mSelectedItem=" +mSelectedItem);
holder.imageView.setImageDrawable(mFilterDrawableList.get(position));
if(position == mSelectedItem)
{
holder.imageView.requestFocus();
holder.imageView.setSelected(true);
Log.e(TAG,"requesting focus=");
//holder.mBgView.setBackgroundResource(R.drawable.button_box_hil);
}
else
{
holder.imageView.setSelected(false);
//holder.mBgView.setBackgroundResource(0);
}
}
#Override
public void onAttachedToRecyclerView(final RecyclerView recyclerView)
{
super.onAttachedToRecyclerView(recyclerView);
mRecyclerView = recyclerView;
}
#Override
public void onItemSelected(AdapterView<?> pParent, View pView, int pPosition, long pId)
{
Log.d(TAG,"onItemSelected " + pPosition);
}
#Override
public int getItemCount()
{
return mFilterDrawableList.size();
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
Log.e(TAG,"onNothingSelected");
}
#Override
public void onAnimationCancel(Animator pAnimator)
{
}
#Override
public void onAnimationEnd(Animator pAnimator)
{
}
#Override
public void onAnimationRepeat(Animator pAnimator)
{
}
#Override
public void onAnimationStart(Animator pAnimator)
{
}
public void moveFocus(int pDirection)
{
int lNextSelect = mSelectedItem + pDirection;
if (lNextSelect >= 0 && lNextSelect < getItemCount())
{
//notifyItemChanged(mSelectedItem);
mSelectedItem = lNextSelect;
//notifyItemChanged(mSelectedItem);
mRecyclerView.smoothScrollToPosition(mSelectedItem);
if(mRecyclerView.getChildAt(mSelectedItem) != null)
{
//mRecyclerView.getChildAt(mSelectedItem).requestFocus();
}
}
else
{
return;
}
setNavigatorText();
setCurrentSelection(mSelectedItem);
int lSelectedList = mCursorIdxList.get(mSelectedItem);
mCacheManager.setCurrentListIdx(lSelectedList);
mListUtil.selectList(lSelectedList);
mNtfHandler.notifyAllObservers(EventID.CH_LIST_REFRESH,null);
}
public void refresh()
{
mRecyclerView.smoothScrollToPosition(mSelectedItem);
int lCurrentList = mCacheManager.getCurrentListIdx();
int lNewSelection = mCursorIdxList.indexOf((Integer)lCurrentList);
Log.d(TAG,"refresh: old selection - "+ mSelectedItem + "new selection - " + lNewSelection);
if(mSelectedItem != lNewSelection)
{
//notifyItemChanged(mSelectedItem);
mSelectedItem = lNewSelection;
//notifyItemChanged(mSelectedItem);
if(mRecyclerView.getChildAt(mSelectedItem) != null)
{
mRecyclerView.getChildAt(mSelectedItem).requestFocus();
}
setNavigatorText();
setCurrentSelection(mSelectedItem);
}
}
}
The above code is my class which extends RecyclerView. Do I have to add some animator to expand the items. If yes where and how ?

Animation on notifyDataSetChanged() in FragmentStatePagerAdapter

By overwriting getItemPosition() method I can refresh my FragmentStatePagerAdapter, which works fine. But the change of the contents is not nice to see.
Is there possibility to apply any kind of animation as I refresh the FragmentStatePagerAdapter?
I was also facing same issue.So, what should you do. Make global variables in your adapter for what you want continuous animate.
Now when you start animation on button click. Pass value to global variables.
When you notifydatasetchanged it doesn't effect your animation.
I haven't found any correct way. So, did this thing.It's working perfect.
public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private ArrayList<Response.DataBean> feedArrayList = new ArrayList<>();
FeedClickListener mListener;
#Inject
ImageUtility mImageUtility;
#Inject
AppUtils mAppUtils;
#Inject
PreferenceManager mPref;
private float prevPosition = -1;
private YoYo.YoYoString ropeText,ropeImage;
private int tempHandlePlayPause = 0;
private TextView tempTextView;
private ImageView tempImageView;
/**
* click listeners
*/
interface FeedClickListener {
void onPlayAudioClicked( FeedResponse.DataBean feedItem, SeekBar audioProgress, int position);
void onPauseAudioClicked(FeedResponse.DataBean feedItem);
}
public HomeAdapter(Context context, ArrayList<Response.DataBean> mDataArrayList, HomeClickListener mFeedListener) {
((BaseApplication) context.getApplicationContext()).getAppComponent().inject(this);
this.mContext = context;
this.feedArrayList = mDataArrayList;
mListener = mFeedListener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false));
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
ItemViewHolder holderItem = (ItemViewHolder) holder;
int adapterPosition = holder.getAdapterPosition() - 1;
holderItem.normalContainer.setVisibility(View.VISIBLE);
holderItem.bannerContainer.setVisibility(View.GONE);
setUpNormalItem(adapterPosition, holderItem);
}
}
private void setUpNormalItem(int adapterPosition, ItemViewHolder holder) {
FeedResponse.DataBean feedItem = feedArrayList.get(adapterPosition);
// set up data to current view holder items
setUpItems(holder, feedItem, adapterPosition);
}
private void setUpItems(ItemViewHolder holder, FeedResponse.DataBean feedItem, int position) {
if (feedItem.isstop()) {
holder.playImageView.setVisibility(View.GONE);
holder.pauseImageView.setVisibility(View.VISIBLE);
} else {
holder.playImageView.setVisibility(View.VISIBLE);
holder.pauseImageView.setVisibility(View.GONE);
holder.audioProgress.setProgress(0);
}
holder.playImageView.setOnClickListener(v -> {
feedItem.setIscomplete(false);
if (prevPosition >= 0) {
feedArrayList.get((int)prevPosition).setIsstop(false);
feedArrayList.get((int)prevPosition).setIsPrepare(false);
}
feedArrayList.get(position).setIsstop(true);
feedArrayList.get(position).setIsPrepare(true);
mListener.onPlayAudioClicked(feedItem, holder.audioProgress, position);
prevPosition = position;
tempHandlePlayPause = 1;
tempTextView = holder.tvPlayingBlink;
tempImageView = holder.pauseImageView;
notifyDataSetChanged();
});
holder.pauseImageView.setOnClickListener(v -> {
feedArrayList.get(position).setIsstop(false);
tempTextView = holder.tvPlayingBlink;
tempImageView = holder.pauseImageView;
tempHandlePlayPause = 0;
mListener.onPauseAudioClicked(feedItem);
notifyDataSetChanged();
});
if (feedItem.isPrepare()) {
holder.tvPlayingBlink.setVisibility(View.VISIBLE);
if (tempHandlePlayPause == 1){
startAnimation();
}else {
stopAnimation();
}
} else {
holder.tvPlayingBlink.setVisibility(View.INVISIBLE);
if (tempHandlePlayPause == 1){
startAnimation();
}else {
stopAnimation();
}
}
// play on complete audio
if (feedItem.iscomplete()) {
holder.playImageView.setVisibility(View.VISIBLE);
holder.pauseImageView.setVisibility(View.GONE);
}
if ((!feedItem.iscomplete()) && feedItem.getTotalLength() > 0) {
holder.audioProgress.setMax(feedItem.getTotalLength());
holder.audioProgress.setProgress(0);
}
}
private void startAnimation(){
if (ropeText != null || ropeImage != null) {
ropeText.stop(true);
ropeImage.stop(true);
}
ropeText = YoYo.with(Techniques.Pulse)
.duration(800)
.repeat(YoYo.INFINITE)
.pivot(YoYo.CENTER_PIVOT, YoYo.CENTER_PIVOT)
.interpolate(new AccelerateDecelerateInterpolator())
.playOn(tempTextView);
ropeImage = YoYo.with(Techniques.Pulse)
.duration(800)
.repeat(YoYo.INFINITE)
.pivot(YoYo.CENTER_PIVOT, YoYo.CENTER_PIVOT)
.interpolate(new AccelerateDecelerateInterpolator())
.playOn(tempImageView);
}
private void stopAnimation(){
if (ropeText != null || ropeImage != null) {
ropeText.stop(true);
ropeImage.stop(true);
}
}
public void updateData(List<FeedResponse.DataBean> items) {
feedArrayList.clear();
feedArrayList.addAll(items);
notifyDataSetChanged();
}
public void deleteItem(int position) {
feedArrayList.remove(position);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return (feedArrayList.size());
}
public static class ItemViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.image_view_3)
ImageView imageView3;
#BindView(R.id.tvplayingblink)
TextView tvPlayingBlink;
public ItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}

Add ProgressBar when recyclerView hit scroll

I have to add Pagination in recyclerView. But I am stuck in adding a progressbar when recyclerView scroll.
I have been trying for a day but unfortunately not got a valid solution to add a progress bar at run time while recyclerView scrolling.I have three ViewHolder.
RecyclerView Scroll Listener
rvRewardItems.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = recyclerView.getChildCount();
int totalItemCount = wrapperLinearLayout.getItemCount();
int firstVisibleItem = wrapperLinearLayout.findFirstVisibleItemPosition();
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount) && !isLoadingMore) {
if (!mStopLoadingData) {
try {
isLoadingMore = true;
// Add item for progress ba
new Handler().post(new Runnable() {
#Override
public void run() {
adapter.addProgressView();
}
});
loadReviews(false, false);
}catch (IllegalStateException e){
e.printStackTrace();
}
}
}
}
});
RewardFinalAdapter.class
public class RewardFinalAdapter extends RecyclerView.Adapter<MainViewHolder>
{
private Context context;
private ArrayList<RewardItemBO> rewardArray;
private OnItemClickListener mItemClickListener;
public static final int VIEW_TYPE_PROGRESS = 0;
public static final int VIEW_TYPE_ITEM = 1;
public static final int VIEW_TYPE_HEADER = 2;
public RewardFinalAdapter(Context context, ArrayList<RewardItemBO> mainItems) {
this.context = context;
rewardArray = getFilterRewards(mainItems);
}
public void resetArray(ArrayList<RewardItemBO> latestArray)
{
rewardArray = getFilterRewards(latestArray);
}
public void setArrayItems(ArrayList<RewardItemBO> latestArray) {
rewardArray = latestArray;
}
#Override
public int getItemViewType(int position) {
if(rewardArray.get(position).isHeader())
return VIEW_TYPE_HEADER;
else if(rewardArray.get(position).isShowProgress())
return VIEW_TYPE_PROGRESS;
else
return VIEW_TYPE_ITEM;
}
#Override
public int getItemCount() {
return rewardArray.size();
}
public RewardItemBO getItem(int position) {
return rewardArray.get(position);
}
public void addItems( ArrayList<RewardItemBO> overallItem){
rewardArray = getFilterRewards(overallItem);
// notifyItemInserted(items.size() - 1);
this.notifyDataSetChanged();
}
// Create new views (invoked by the layout manager)
#Override
public MainViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
switch (viewType){
case VIEW_TYPE_HEADER:
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.order_list_header, viewGroup, false);
return new RewardListViewHolderHeader(itemView);
case VIEW_TYPE_ITEM:
View view = LayoutInflater.from(context).inflate(R.layout.item_rewards, viewGroup, false);
return new RewardViewHolder(view);
case VIEW_TYPE_PROGRESS:
Log.v("view_type_progress","I am in VIEW_TYPE_PROGRESS");
View progressView = LayoutInflater.from(context).inflate(R.layout.progress_loader, viewGroup, false);
return new ProgressViewHolder(progressView);
}
return null;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(MainViewHolder viewHolder, int position) {
RewardItemBO rewardItemBO= rewardArray.get(position);
if(viewHolder instanceof RewardViewHolder)
{
RewardViewHolder rewardViewHolder=(RewardViewHolder) viewHolder;
rewardViewHolder.tvRewardTitle.setText(rewardArray.get(position).getRewardTitle());
rewardViewHolder.tvRewardDescription.setText(rewardArray.get(position).getRewardMessage());
String formatedDate = DateTimeOp.oneFormatToAnother(rewardArray.get(position).getRewardExpiryDate(), Constants.dateFormat18, Constants.dateFormat6);
rewardViewHolder.tvRewardExpiry.setText("Expires " + formatedDate);
if(rewardArray.get(position).getRewardShowRedeem().equals("1"))
{
rewardViewHolder.btnGrey.setVisibility(View.VISIBLE);
rewardViewHolder.btnGrey.setText("Redeemed");
}
else if(rewardArray.get(position).getRewardExpired().equals("1"))
{
rewardViewHolder.btnGrey.setVisibility(View.VISIBLE);
rewardViewHolder.btnGrey.setText("Expired");
}
else
{
rewardViewHolder.btnOrange.setVisibility(View.VISIBLE);
rewardViewHolder.btnOrange.setText("Get Code");
}
}
else if(viewHolder instanceof RewardListViewHolderHeader)
{
RewardListViewHolderHeader holder = (RewardListViewHolderHeader ) viewHolder;
holder.tvHeader.setText(rewardItemBO.getHeaderTitle());
}
else if(viewHolder instanceof ProgressViewHolder)
{
ProgressViewHolder progressViewHolder = (ProgressViewHolder) viewHolder;
progressViewHolder.progressBar.setIndeterminate(true);
}
}
public void addOnTop(ArrayList<RewardItemBO> topItemList) {
Collections.reverse(topItemList);
rewardArray.addAll(0, topItemList);
notifyItemRangeInserted(0, topItemList.size());
}
public interface OnItemClickListener {
public void onItemClick(View view , int position);
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
#Override
public long getItemId(int position) {
return position;
}
public ArrayList<RewardItemBO> getFilterRewards(ArrayList<RewardItemBO> mainItems){
ArrayList<RewardItemBO> currentRewardList = new ArrayList<RewardItemBO>();
ArrayList<RewardItemBO> pastRewardList = new ArrayList<RewardItemBO>();
ArrayList<RewardItemBO> dummyArray = new ArrayList<>();
for (RewardItemBO rewardItemBO : mainItems) {
try {
//because reward item with progress have everything null in it.
if(rewardItemBO.getRewardExpired()!=null && !rewardItemBO.isShowProgress())
{
int isExpired = Integer.parseInt(rewardItemBO.getRewardExpired());
if(isExpired==1)
pastRewardList.add(rewardItemBO);
else
currentRewardList.add(rewardItemBO);
}
}catch (NumberFormatException e){
e.printStackTrace();
}
}
if(currentRewardList.size()>0){
currentRewardList.add(0, new RewardItemBO(context.getResources().getString(R.string.Current)));
dummyArray.addAll(currentRewardList);
}
if(pastRewardList.size()>0){
pastRewardList.add(0, new RewardItemBO(context.getResources().getString(R.string.Past)));
dummyArray.addAll(pastRewardList);
}
return dummyArray;
}
public void addProgressView()
{
rewardArray.add(new RewardItemBO(true));
//notifyItemChanged(rewardArray.size());
notifyDataSetChanged();
}
public void removeProgressView(){
int position = rewardArray.size() -1;
rewardArray.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, rewardArray.size());
}
public static class RewardListViewHolderHeader extends MainViewHolder {
protected TextView tvHeader;
public RewardListViewHolderHeader (View v) {
super(v);
tvHeader = (TextView) v.findViewById(R.id.header_text);
}
}
public class RewardViewHolder extends MainViewHolder implements View.OnClickListener{
public TextView tvRewardTitle;
public TextView tvRewardDescription;
public TextView tvRewardExpiry;
public Button btnOrange,btnGrey;
public RewardViewHolder(View v) {
super(v);
tvRewardTitle = (TextView) itemView.findViewById(R.id.tv_reward_title);
tvRewardDescription = (TextView) itemView.findViewById(R.id.tv_reward_description);
tvRewardExpiry = (TextView) itemView.findViewById(R.id.tv_reward_expiry_date);
btnOrange = (Button) itemView.findViewById(R.id.btn_item_reward_orange);
btnGrey = (Button) itemView.findViewById(R.id.btn_item_reward_grey);
btnOrange.setOnClickListener(this);
btnGrey.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//Toast.makeText(context, tvName.getText().toString(), Toast.LENGTH_SHORT).show();
if (mItemClickListener != null) {
mItemClickListener.onItemClick(v,getAdapterPosition());
}
}
}
}

Categories

Resources