notifyItemChanged method does not call onBindViewHolder in recyclerview - android

My code is as shown below:
public class PopularItemsAdapter extends RecyclerView.Adapter<PopularItemsAdapter.MyViewHolder>
implements MyCartListener {
private Context mContext;
private List<FoodTruckItem> foodTruckItemList;
private boolean isClickable = false;
private OnItemClickListener listener;
private List<FoodtruckInfo> foodtruckInfoList = new ArrayList<>();
private List<FoodTruckItem> sessionItem = new ArrayList<>();
private boolean isConflictResolved = false;
public int position = -1;
#Override
public void itemUpdated(int quantity, String itemId) {
for (int i = 0; i < foodTruckItemList.size(); i++) {
if (itemId.equals(foodTruckItemList.get(i).getItemId())) {
foodTruckItemList.get(i).setItemQuantityOrdered(quantity);
// notifyDataSetChanged();
}
}
}
#Override
public void itemRemoved(String itemId) {
for (int j = 0; j < foodTruckItemList.size(); j++) {
if (itemId.equals(foodTruckItemList.get(j).getItemId())) {
foodTruckItemList.remove(j);
// notifyDataSetChanged();
}
}
}
public void addConflictItem(int position) {
isConflictResolved = true;
notifyItemChanged(position);
}
public interface OnItemClickListener {
void onItemClick(FoodTruckItem foodTruckItem, FoodtruckInfo foodtruckInfo);
void showSnackBar(int items, boolean added, int position);
void showRestaurentClosed();
void showWarningDialog(int position);
}
public void addFoodInfo(List<FoodtruckInfo> foodtruckInfos) {
foodtruckInfoList.addAll(foodtruckInfos);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView itemName, foodPrice, addText, quantityText, addQuantity, removeQuantity;
public ImageView itemImage, itemTag;
public LinearLayout addLayout;
public MyViewHolder(View view) {
super(view);
itemTag = (ImageView) view.findViewById(R.id.itemTag);
itemImage = (ImageView) view.findViewById(R.id.itemImage);
itemName = (TextView) view.findViewById(R.id.itemName);
foodPrice = (TextView) view.findViewById(R.id.foodPrice);
addText = (TextView) view.findViewById(R.id.addText);
addLayout = (LinearLayout) view.findViewById(R.id.addLayout);
quantityText = (TextView) view.findViewById(R.id.quantityText);
addQuantity = (TextView) view.findViewById(R.id.addQuantity);
removeQuantity = (TextView) view.findViewById(R.id.removeQuantity);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
//passing the clicked position to the parent class
for (FoodtruckInfo info : foodtruckInfoList) {
if (info.getItemId().equals(foodTruckItemList.get(getAdapterPosition()).getItemId())) {
foodtruckInfo = info;
}
}
listener.onItemClick(foodTruckItemList.get(getAdapterPosition()), foodtruckInfo);
}
}
public PopularItemsAdapter(Context mContext, List<FoodTruckItem> foodTruckItemList, OnItemClickListener listener) {
this.mContext = mContext;
this.foodTruckItemList = foodTruckItemList;
this.listener = listener;
MyCart.getInstance().addListener(this);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_popular_items, parent, false);
return new MyViewHolder(itemView);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final FoodTruckItem foodTruckItem = foodTruckItemList.get(position);
if (SessionManager.get(mContext).getFoodTruckItemList() != null) {
sessionItem = SessionManager.get(mContext).getFoodTruckItemList();
for (FoodTruckItem item : sessionItem) {
if (item.getItemId().equals(foodTruckItem.getItemId())) {
// holder.itemTag.setText("MY FAVOURITE");
holder.itemTag.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_favorite));
}
}
}
holder.itemName.setText(foodTruckItem.getItemName());
// holder.itemTag.setText(foodTruckItem.getSpecialTag());
holder.foodPrice.setText("$" + String.valueOf(foodTruckItem.getItemPrice()));
Picasso.Builder builder = new Picasso.Builder(mContext);
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
if (!TextUtils.isEmpty(foodTruckItem.getItemImg())) {
builder.build().load(foodTruckItem.getItemImg()).into(holder.itemImage);
}
holder.addText.setOnClickListener(new View.OnClickListener() {
FoodtruckInfo info = new FoodtruckInfo();
#Override
public void onClick(View v) {
for (int l = 0; l < foodtruckInfoList.size(); l++) {
if (foodtruckInfoList.get(l).getItemId().equals(foodTruckItem.getItemId())) {
if (foodtruckInfoList.get(l).getOrderStatus() == 0) {
isClickable = true;
} else {
isClickable = false;
}
}
}
if (isClickable) {
String foodTruckId = null;
if (MyCart.getInstance().getFoodTruckId() != null) {
foodTruckId = MyCart.getInstance().getFoodTruckId();
if (!foodTruckId.equals(foodtruckInfoList.get(position).getFoodTruckId())) {
listener.showWarningDialog(position);
} else {
addItem(holder, position, foodTruckItem);
}
} else {
isConflictResolved = false;
addItem(holder, position, foodTruckItem);
}
} else {
listener.showRestaurentClosed();
}
if (isConflictResolved) {
isConflictResolved = false;
addItem(holder, position, foodTruckItem);
}
}
});
holder.addQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = foodTruckItem.getItemQuantityOrdered();
quantity += 1;
holder.quantityText.setText(String.valueOf(quantity));
MyCart.getInstance().updateQuantity(quantity, foodTruckItem.getItemId(), false);
}
});
holder.removeQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = foodTruckItem.getItemQuantityOrdered();
quantity -= 1;
if (quantity == 0) {
MyCart.getInstance().removeItem(foodTruckItem.getItemId(), false);
holder.addLayout.setVisibility(View.INVISIBLE);
holder.addText.setVisibility(View.VISIBLE);
listener.showSnackBar(quantity, false, position);
} else {
holder.quantityText.setText(String.valueOf(quantity));
MyCart.getInstance().updateQuantity(quantity, foodTruckItem.getItemId(), false);
}
}
});
setFontStyle(holder);
}
private void addItem(MyViewHolder holder, int position, FoodTruckItem foodTruckItem) {
holder.addLayout.setVisibility(View.VISIBLE);
holder.addText.setVisibility(View.INVISIBLE);
foodTruckItem.setItemQuantityOrdered(1);
holder.quantityText.setText(String.valueOf(1));
MyCart.getInstance().addItem(foodTruckItem);
MyCart.getInstance().setFoodTruckId(foodtruckInfoList.get(position).getFoodTruckId());
listener.showSnackBar(MyCart.getInstance().getItemList(), true, position);
}
private void setFontStyle(MyViewHolder holder) {
holder.itemName.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
// holder.itemTag.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
holder.foodPrice.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
holder.addText.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
}
#Override
public int getItemCount() {
return foodTruckItemList.size();
}
}
Here addConflictItem() I have written notifyItemChanged , but somehow it is not calling onBindViewHolder , so is there anything missing in the application?

I was having the same problem, and this worked for me, just add those line to your recyclerview declaration, see this Asnswer
DefaultItemAnimator animator = new DefaultItemAnimator() {
#Override
public boolean canReuseUpdatedViewHolder(RecyclerView.ViewHolder viewHolder) {
return true;
}
};
mRecyclerView.setItemAnimator(animator);

As my experience using setOnClickListener in onBindViewHolder is not good idea.
public class PopularItemsAdapter extends RecyclerView.Adapter<PopularItemsAdapter.MyViewHolder>
implements MyCartListener {
private Context mContext;
private List<FoodTruckItem> foodTruckItemList;
private boolean isClickable = false;
private OnItemClickListener listener;
private List<FoodtruckInfo> foodtruckInfoList = new ArrayList<>();
private List<FoodTruckItem> sessionItem = new ArrayList<>();
private boolean isConflictResolved = false;
public int position = -1;
#Override
public void itemUpdated(int quantity, String itemId) {
for (int i = 0; i < foodTruckItemList.size(); i++) {
if (itemId.equals(foodTruckItemList.get(i).getItemId())) {
foodTruckItemList.get(i).setItemQuantityOrdered(quantity);
// notifyDataSetChanged();
}
}
}
#Override
public void itemRemoved(String itemId) {
for (int j = 0; j < foodTruckItemList.size(); j++) {
if (itemId.equals(foodTruckItemList.get(j).getItemId())) {
foodTruckItemList.remove(j);
// notifyDataSetChanged();
}
}
}
public void addConflictItem(int position) {
isConflictResolved = true;
notifyItemChanged(position);
}
public interface OnItemClickListener {
void onItemClick(FoodTruckItem foodTruckItem, FoodtruckInfo foodtruckInfo);
void showSnackBar(int items, boolean added, int position);
void showRestaurentClosed();
void showWarningDialog(int position);
}
public void addFoodInfo(List<FoodtruckInfo> foodtruckInfos) {
foodtruckInfoList.addAll(foodtruckInfos);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView itemName, foodPrice, addText, quantityText, addQuantity, removeQuantity;
public ImageView itemImage, itemTag;
public LinearLayout addLayout;
MyViewHolder holder;
public MyViewHolder(View view) {
super(view);
itemTag = (ImageView) view.findViewById(R.id.itemTag);
itemImage = (ImageView) view.findViewById(R.id.itemImage);
itemName = (TextView) view.findViewById(R.id.itemName);
foodPrice = (TextView) view.findViewById(R.id.foodPrice);
addText = (TextView) view.findViewById(R.id.addText);
addLayout = (LinearLayout) view.findViewById(R.id.addLayout);
quantityText = (TextView) view.findViewById(R.id.quantityText);
addQuantity = (TextView) view.findViewById(R.id.addQuantity);
removeQuantity = (TextView) view.findViewById(R.id.removeQuantity);
holder = this;
view.setOnClickListener(this);
addText.setOnClickListener(new View.OnClickListener() {
FoodtruckInfo info = new FoodtruckInfo();
#Override
public void onClick(View v) {
int position = getAdapterPosition;
for (int l = 0; l < foodtruckInfoList.size(); l++) {
if (foodtruckInfoList.get(l).getItemId().equals(foodTruckItem.getItemId())) {
if (foodtruckInfoList.get(l).getOrderStatus() == 0) {
isClickable = true;
} else {
isClickable = false;
}
}
}
if (isClickable) {
String foodTruckId = null;
if (MyCart.getInstance().getFoodTruckId() != null) {
foodTruckId = MyCart.getInstance().getFoodTruckId();
if (!foodTruckId.equals(foodtruckInfoList.get(position).getFoodTruckId())) {
listener.showWarningDialog(position);
} else {
addItem(holder, position, foodTruckItem);
}
} else {
isConflictResolved = false;
addItem(holder, position, foodTruckItem);
}
} else {
listener.showRestaurentClosed();
}
if (isConflictResolved) {
isConflictResolved = false;
addItem(holder, position, foodTruckItem);
}
}
});
removeQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition;
int quantity = foodTruckItem.getItemQuantityOrdered();
quantity -= 1;
if (quantity == 0) {
MyCart.getInstance().removeItem(foodTruckItem.getItemId(), false);
holder.addLayout.setVisibility(View.INVISIBLE);
holder.addText.setVisibility(View.VISIBLE);
listener.showSnackBar(quantity, false, position);
} else {
holder.quantityText.setText(String.valueOf(quantity));
MyCart.getInstance().updateQuantity(quantity, foodTruckItem.getItemId(), false);
}
}
});
addQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition;
int quantity = foodTruckItem.getItemQuantityOrdered();
quantity += 1;
holder.quantityText.setText(String.valueOf(quantity));
MyCart.getInstance().updateQuantity(quantity, foodTruckItem.getItemId(), false);
}
});
}
#Override
public void onClick(View view) {
FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
//passing the clicked position to the parent class
for (FoodtruckInfo info : foodtruckInfoList) {
if (info.getItemId().equals(foodTruckItemList.get(getAdapterPosition()).getItemId())) {
foodtruckInfo = info;
}
}
listener.onItemClick(foodTruckItemList.get(getAdapterPosition()), foodtruckInfo);
}
}
public PopularItemsAdapter(Context mContext, List<FoodTruckItem> foodTruckItemList, OnItemClickListener listener) {
this.mContext = mContext;
this.foodTruckItemList = foodTruckItemList;
this.listener = listener;
MyCart.getInstance().addListener(this);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_popular_items, parent, false);
return new MyViewHolder(itemView);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final FoodTruckItem foodTruckItem = foodTruckItemList.get(position);
if (SessionManager.get(mContext).getFoodTruckItemList() != null) {
sessionItem = SessionManager.get(mContext).getFoodTruckItemList();
for (FoodTruckItem item : sessionItem) {
if (item.getItemId().equals(foodTruckItem.getItemId())) {
// holder.itemTag.setText("MY FAVOURITE");
holder.itemTag.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_favorite));
}
}
}
holder.itemName.setText(foodTruckItem.getItemName());
// holder.itemTag.setText(foodTruckItem.getSpecialTag());
holder.foodPrice.setText("$" + String.valueOf(foodTruckItem.getItemPrice()));
Picasso.Builder builder = new Picasso.Builder(mContext);
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
if (!TextUtils.isEmpty(foodTruckItem.getItemImg())) {
builder.build().load(foodTruckItem.getItemImg()).into(holder.itemImage);
}
setFontStyle(holder);
}
private void addItem(MyViewHolder holder, int position, FoodTruckItem foodTruckItem) {
holder.addLayout.setVisibility(View.VISIBLE);
holder.addText.setVisibility(View.INVISIBLE);
foodTruckItem.setItemQuantityOrdered(1);
holder.quantityText.setText(String.valueOf(1));
MyCart.getInstance().addItem(foodTruckItem);
MyCart.getInstance().setFoodTruckId(foodtruckInfoList.get(position).getFoodTruckId());
listener.showSnackBar(MyCart.getInstance().getItemList(), true, position);
}
private void setFontStyle(MyViewHolder holder) {
holder.itemName.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
// holder.itemTag.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
holder.foodPrice.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
holder.addText.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
}
#Override
public int getItemCount() {
return foodTruckItemList.size();
}
}

Just call notifyDataSetChanged() and the RecycleView will refresh

Related

recyclerView whit multi view type get messed up on scrolling

i have a recyclerView which contains three type of view ; in the view type 2 i am checking if the file exits on the internal storage so i load it from storage and if
it is not i show a small image view in center of view to download it . when user click download image view the image changes from download icon to pause icon but this happen for some other rows ...
the mainly accepted answers to this question are
holder.setIsRecyclable(false);
but this ruin the purpose of recyclerView
2.override this methods
#Override public long getItemId(int position) {
return position; }
#Override public int getItemViewType(int position) {
return position; }
and my code
#Override
public int getItemViewType(int position) {
int type = messages.get(position).getType();
if (type==1) {
return 1;
}else if (type==2) {
return 2 ;
}else if (type==3) {
return 3;
}
else {
return -1;
}
}
#Override
public long getItemId(int position) {
return position;
}
setHasStableIds(true);
not Working
4.write both if and else conditions in onBindViewHolder
switch (holder.getItemViewType()) {
case 1 :
SimpleHolder simpleHolder = (SimpleHolder)holder;
simpleHolder.tv_text.setText(message.getMessage());
simpleHolder.tv_time.setText(time);
if (message.getLiked()==0) {
simpleHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.unlike));
}else {
simpleHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.like));
}
break;
case 2 :
ImageHolder imageHolder = (ImageHolder)holder;
//in method esme folder va esme aks ro migire o check mikone bebine mojode ya na
if (isFileExists(Config.Folders.IMAGES ,message.getUrl())) {
imageHolder.circularProgressBar.setVisibility(View.GONE);
imageHolder.iv_download.setVisibility(View.GONE);
Glide.with(context).load(getFile(Config.Folders.IMAGES,message.getUrl())).apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
) .into(new SimpleTarget<Drawable>() {
#Override
public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
((ImageHolder) holder).iv_picture.setImageDrawable(resource);
}
});
imageHolder.iv_picture.setImageURI(Uri.fromFile(getFile(Config.Folders.IMAGES,message.getUrl())));
}else {
imageHolder.iv_download.setVisibility(View.VISIBLE);
imageHolder.circularProgressBar.setVisibility(View.VISIBLE);
Glide.with(context).load(Config.MESSAGE_THUMB_ADDRESS+message.getThumb()).apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(ContextCompat.getDrawable(context,R.drawable.white))
).into(imageHolder.iv_picture);
}
imageHolder.tv_time.setText(time);
if (message.getMessage()!=null) {
imageHolder.tv_text.setVisibility(View.VISIBLE);
imageHolder.tv_text.setText(message.getMessage());
}else {
imageHolder.tv_text.setVisibility(View.GONE);
}
if (message.getLiked()==0) {
imageHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.unlike));
}else {
imageHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.like));
}
break;
but still none of them works
the whole code of my adapter class is
public class Message_Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
ArrayList<Message> messages;
ClickListener clickListener;
public Message_Adapter(Context context, ArrayList<Message> messages) {
this.context = context;
this.messages = messages;
setHasStableIds(true);
}
public interface ClickListener {
public void picture_imageClicked(int position, View view, CircularProgressBar circularProgressBar, ImageView iv_download);
public void picture_likeClicked(int position, View view);
public void picture_commentClicked(int position, View view);
public void simple_likeClicked(int position, View view);
public void simple_commentClicked(int position, View view);
public void video_imageClicked(int position, View view, CircularProgressBar circularProgressBar, ImageView iv_download);
public void video_likeClicked(int position, View view);
public void video_commentClicked(int position, View view);
}
public void setCliclListener(ClickListener cliclListener) {
this.clickListener = cliclListener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 1) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_simple, parent, false);
return new SimpleHolder(view);
} else if (viewType == 2) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_picture, parent, false);
CircularProgressBar circularProgressBar = (CircularProgressBar) view.findViewById(R.id.cp_picturee);
circularProgressBar.setColor(ContextCompat.getColor(context, android.R.color.holo_blue_dark));
circularProgressBar.setBackgroundColor(ContextCompat.getColor(context, android.R.color.holo_blue_dark));
circularProgressBar.setProgressBarWidth(10);
circularProgressBar.setBackgroundProgressBarWidth(5);
int animationDuration = 2500; // 2500ms = 2,5s
// circularProgressBar.setProgressWithAnimation(65, animationDuration);
return new ImageHolder(view);
} else if (viewType == 3) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_video, parent, false);
CircularProgressBar circularProgressBar = (CircularProgressBar) view.findViewById(R.id.cp_video);
circularProgressBar.setColor(ContextCompat.getColor(context, android.R.color.holo_blue_dark));
circularProgressBar.setBackgroundColor(ContextCompat.getColor(context, android.R.color.holo_blue_dark));
circularProgressBar.setProgressBarWidth(10);
circularProgressBar.setBackgroundProgressBarWidth(5);
return new VideoHolder(view);
} else {
throw new RuntimeException("The type has to be ONE or TWO");
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
Message message = messages.get(position);
String time = "00:00";
Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(message.getUpdated_at());
time = new SimpleDateFormat("H:mm").format(date);
} catch (ParseException e) {
e.printStackTrace();
}
switch (holder.getItemViewType()) {
case 1:
SimpleHolder simpleHolder = (SimpleHolder) holder;
simpleHolder.tv_text.setText(message.getMessage());
simpleHolder.tv_time.setText(time);
if (message.getLiked() == 0) {
simpleHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.unlike));
} else {
simpleHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.like));
}
break;
case 2:
ImageHolder imageHolder = (ImageHolder) holder;
//in method esme folder va esme aks ro migire o check mikone bebine mojode ya na
if (isFileExists(Config.Folders.IMAGES, message.getUrl())) {
imageHolder.circularProgressBar.setVisibility(View.GONE);
imageHolder.iv_download.setVisibility(View.GONE);
Glide.with(context).load(getFile(Config.Folders.IMAGES, message.getUrl())).apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
).into(new SimpleTarget<Drawable>() {
#Override
public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
((ImageHolder) holder).iv_picture.setImageDrawable(resource);
}
});
imageHolder.iv_picture.setImageURI(Uri.fromFile(getFile(Config.Folders.IMAGES, message.getUrl())));
} else {
imageHolder.iv_download.setVisibility(View.VISIBLE);
imageHolder.circularProgressBar.setVisibility(View.VISIBLE);
Glide.with(context).load(Config.MESSAGE_THUMB_ADDRESS + message.getThumb()).apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(ContextCompat.getDrawable(context, R.drawable.white))
).into(imageHolder.iv_picture);
}
imageHolder.tv_time.setText(time);
if (message.getMessage() != null) {
imageHolder.tv_text.setVisibility(View.VISIBLE);
imageHolder.tv_text.setText(message.getMessage());
} else {
imageHolder.tv_text.setVisibility(View.GONE);
}
if (message.getLiked() == 0) {
imageHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.unlike));
} else {
imageHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.like));
}
break;
case 3:
VideoHolder videoHolder = (VideoHolder) holder;
videoHolder.tv_time.setText(time);
if (message.getMessage() != null) {
videoHolder.tv_text.setVisibility(View.VISIBLE);
videoHolder.tv_text.setText(message.getMessage());
} else {
videoHolder.tv_text.setVisibility(View.GONE);
}
if (message.getLiked() == 0) {
videoHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.unlike));
} else {
videoHolder.iv_like.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.like));
}
Glide.with(context).load(Config.VIDEO_PIC_ADDRES + message.getThumb()).apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
).into(videoHolder.iv_picture);
if (isFileExists(Config.Folders.VIDEOS, message.getUrl())) {
videoHolder.circularProgressBar.setVisibility(View.INVISIBLE);
videoHolder.iv_download.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.play));
} else {
videoHolder.iv_download.setVisibility(View.VISIBLE);
videoHolder.circularProgressBar.setVisibility(View.VISIBLE);
videoHolder.iv_download.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.download));
}
String lenth = message.getLenth() < 1024 ? message.getLenth() + " kb" : message.getLenth() / 1024 + " mb";
videoHolder.tv_video_time.setText(message.getTime() + " | " + lenth);
break;
default:
break;
}
}
public boolean isFileExists(String folderName, String filename) {
if (filename == null) {
filename = "null";
}
File file = new File(Environment.getExternalStorageDirectory() + "/NoorAlSalehin/" + folderName, filename);
return file.exists();
}
public File getFile(String folderName, String filename) {
File file = new File(Environment.getExternalStorageDirectory() + "/NoorAlSalehin/" + folderName, filename);
return file;
}
#Override
public int getItemCount() {
return messages.size();
}
#Override
public int getItemViewType(int position) {
int type = messages.get(position).getType();
if (type == 1) {
return 1;
} else if (type == 2) {
return 2;
} else if (type == 3) {
return 3;
} else {
return -1;
}
}
#Override
public long getItemId(int position) {
return position;
}
class SimpleHolder extends RecyclerView.ViewHolder {
TextView tv_text, tv_time;
ImageView iv_like, iv_comment;
public SimpleHolder(View itemView) {
super(itemView);
tv_text = (TextView) itemView.findViewById(R.id.tv_custom_simple_text);
iv_like = (ImageView) itemView.findViewById(R.id.iv_simple_like);
iv_comment = (ImageView) itemView.findViewById(R.id.iv_simple_comment);
tv_time = (TextView) itemView.findViewById(R.id.tv_simple_time);
iv_like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.simple_likeClicked(getAdapterPosition(), view);
}
});
iv_comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.simple_commentClicked(getAdapterPosition(), view);
}
});
}
}
class ImageHolder extends RecyclerView.ViewHolder {
ImageView iv_picture, iv_download, iv_like, iv_comment;
TextView tv_text, tv_time;
CircularProgressBar circularProgressBar;
public ImageHolder(View itemView) {
super(itemView);
iv_download = (ImageView) itemView.findViewById(R.id.iv_picture_download);
iv_picture = (ImageView) itemView.findViewById(R.id.iv_picture_image);
circularProgressBar = (CircularProgressBar) itemView.findViewById(R.id.cp_picturee);
tv_text = (TextView) itemView.findViewById(R.id.tv_picture_text);
iv_comment = (ImageView) itemView.findViewById(R.id.iv_picture_comment);
tv_time = (TextView) itemView.findViewById(R.id.tv_picture_time);
iv_picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.picture_imageClicked(getAdapterPosition(), view, circularProgressBar, iv_download);
}
});
iv_like = (ImageView) itemView.findViewById(R.id.iv_picture_like);
iv_like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.picture_likeClicked(getAdapterPosition(), view);
}
});
iv_comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.picture_commentClicked(getAdapterPosition(), view);
}
});
}
}
class VideoHolder extends RecyclerView.ViewHolder {
// ImageView iv_picture , iv_like , iv_comment;
ImageView iv_picture, iv_download, iv_like, iv_comment;
TextView tv_text, tv_time, tv_video_time;
// CircleProgressView circleProgressView ;
CircularProgressBar circularProgressBar;
public VideoHolder(View itemView) {
super(itemView);
iv_download = (ImageView) itemView.findViewById(R.id.iv_video_download_playy);
iv_picture = (ImageView) itemView.findViewById(R.id.iv_video_image);
// circleProgressView=(CircleProgressView)itemView.findViewById(R.id.cp_video_download);
circularProgressBar = (CircularProgressBar) itemView.findViewById(R.id.cp_video);
tv_text = (TextView) itemView.findViewById(R.id.tv_video_text);
iv_comment = (ImageView) itemView.findViewById(R.id.iv_video_comment);
tv_time = (TextView) itemView.findViewById(R.id.tv_video_time);
iv_picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.video_imageClicked(getAdapterPosition(), view, circularProgressBar, iv_download);
}
});
tv_video_time = (TextView) itemView.findViewById(R.id.tv_video_video_time);
iv_like = (ImageView) itemView.findViewById(R.id.iv_video_like);
iv_like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.video_likeClicked(getAdapterPosition(), view);
}
});
iv_comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.video_commentClicked(getAdapterPosition(), view);
}
});
}
}
}

Update the value from one adapter to another expandable listview in android

I am getting value from checking page adapter.If click the plus image in one list item the count value get increase.I want to update that particular value of child item in expandablelistview adapter.How to update that particular child value from checking page adapter.
Checkinapadater:
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Movie1 m = movieItems.get(position);
if (m.getfood_totalprice() != null) {
if (!m.getfood_totalprice().equals("null")) {
holder.amount.setText(m.getfood_totalprice());
}
}
if (m.getfood_count() != null) {
if (!m.getfood_count().equals("null")) {
holder.item_count.setText(m.getfood_count());
}
}
holder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int i = Integer.parseInt(holder.item_count.getText().toString());
if(i>=0){
int count = i + 1;
holder.item_count.setText(Integer.toString(count));
value = Integer.toString(count);
}
});
holder.minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int i = Integer.parseInt(holder.item_count.getText().toString());
if(i>0){
int count = i - 1;
holder.item_count.setText(Integer.toString(count));
}
});
}
Exapanadablelistapater:
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final Child child = (Child) getChild(groupPosition, childPosition);
final Child modelChild = groups.get(groupPosition).getItems().get(childPosition);
if (convertView == null) {
LayoutInflater inflator = LayoutInflater.from(parent.getContext());
convertView = inflator.inflate(R.layout.detail_list, null);
viewHolder = new ViewHolder();
viewHolder.minus = (ImageView) convertView.findViewById(R.id.minus);
viewHolder.plus = (ImageView) convertView.findViewById(R.id.plus);
viewHolder.green = (ImageView) convertView.findViewById(R.id.green);
viewHolder.red = (ImageView) convertView.findViewById(R.id.red);
viewHolder.item_count = (TextView) convertView.findViewById(R.id.count);
//viewHolder.txtView = (TextView) ((AppCompatActivity)context).findViewById(R.id.checked_item);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv.setText(child.getName());
viewHolder.amount.setText(child.getPrice());
viewHolder.item_count.setText(Integer.toString(child.getCount()));
viewHolder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(modelChild.getCount()>=0) // set your count default 0 when you bind data initially
{
int count = (modelChild.getCount()) + 1;
modelChild.setCount(count);
int s= Integer.parseInt(Detailpage.item.getText().toString());
itemname.setText(Integer.toString(count1));
// viewHolder.txtView.setText(Integer.toString(count1)+"items");
count1=s+1;
Detailpage.item.setText(Integer.toString(count1));
int foodprice=0;
foodprice=Integer.parseInt(child.getPrice());
total1=child.getPrice();
value=Integer.toString(modelChild.getcount());
//
name = modelChild.getName();
id=child.getId();
new AsyncT().execute(user_id,res_id,id,name,total1,value);
groups.get(groupPosition).getItems().set(childPosition, modelChild);
notifyDataSetChanged();
}
}});
viewHolder.minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(modelChild.getCount()>0) // set your count default 0 when you bind data initially
{ int count = modelChild.getCount() - 1;
modelChild.setCount(count);
int s= Integer.parseInt(Detailpage.item.getText().toString());
count1=s-1;
Detailpage.item.setText(Integer.toString(count1));
name=modelChild.getName();
//
int foodprice=0;
foodprice=Integer.parseInt(child.getPrice());
int total = foodprice * child.getcount();
total1=child.getPrice();
// total1=Integer.toString(total);
value=Integer.toString(count);
id=child.getId();
if(count>0) {
new AsyncT().execute(user_id, res_id, id, name, total1, value);
}
}
modelChild.setChildName(modelChild.getChildName());
// set your other items if any like above
groups.get(groupPosition).getItems().set(childPosition, modelChild);
notifyDataSetChanged();
}
});
return convertView;
}
Movie1 model(checkin page):`
public class Movie1 {
public String food_id,food_count,food_item,food_price,food_resid,food_totalprice;
public void setfood_id(String food_id) {
this.food_id = food_id;
}
public void setfood_count(String food_count) {
this.food_count = food_count;
}
public void setfood_price(String food_price) {
this.food_price = food_price;
}
public void setfood_item(String food_item) {
this.food_item = food_item;
}
public String getfood_item() {
return food_item;
}
public String getfood_count() {
return food_count;
}
public String getfood_price() {
return food_price;
}
public void setfood_resid(String food_resid) {
this.food_resid = food_resid;
}
public String getfood_resid() {
return food_resid;
}
public String getfood_id() {
return food_id;
}
public void setfood_totalprice(String food_totalprice) {
this.food_totalprice = food_totalprice;
}
public String getfood_totalprice() {
return food_totalprice;
}
}
`
Child model:(Expandable listview)
public class Child {
private String Name,childName,item_status,image1,available_from,available_to,price,id,status;
private int Image,count;
public Object getstatus;
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public int getImage() {
return Image;
}
public void setImage(int Image) {
this.Image = Image;
}
public void setcount(int count) {
this.count = count;
}
public int getcount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getChildName() {
return childName;
}
public int getCount() {
return count;
}
public void setChildName(String childName) {
this.childName = childName;
}
public void setItem_status(String item_status) {
this.item_status = item_status;
}
public void setImage1(String image1) {
this.image1 = image1;
}
public void setAvailable_to(String available_to) {
this.available_to = available_to;
}
public void setAvailable_from(String available_from) {
this.available_from = available_from;
}
public void setPrice(String price) {
this.price = price;
}
public void setId(String id) {
this.id = id;
}
public String getPrice() {
return price;
}
public String getImage1() {
return image1;
}
public String getItem_status() {
return item_status;
}
public String getId() {
return id;
}
public void setstatus(String status) {
this.status = status;
}
public String getstatus() {
return status;
}
}
`checkin
Expandablelist adapter

ExpandableRecyclerAdapter How to force item to move up while expanding an item

This is my ExpandableRecyclerAdapter adapter
public class MyAdapter extends ExpandableRecyclerAdapter<MyAdapter.ProductParentViewHolder, MyAdapter.ProductChildViewHolder> {
private LayoutInflater mInflater;
private Context context;
private List<? extends ParentListItem> mParentItemList;
public MyAdapter(Context context, List<ParentListItem> itemList) {
super(itemList);
mInflater = LayoutInflater.from(context);
this.context = context;
this.mParentItemList = itemList;
}
#Override
public ProductParentViewHolder onCreateParentViewHolder(ViewGroup viewGroup) {
View view = mInflater.inflate(R.layout.list_item_crime_parent, viewGroup, false);
return new ProductParentViewHolder(view);
}
#Override
public ProductChildViewHolder onCreateChildViewHolder(ViewGroup viewGroup) {
View view = mInflater.inflate(R.layout.list_item_crime_child, viewGroup, false);
return new ProductChildViewHolder(view);
}
#Override
public void onBindParentViewHolder(ProductParentViewHolder crimeParentViewHolder, int i, ParentListItem parentListItem) {
Product product = (Product) parentListItem;
crimeParentViewHolder.productName.setText(product.getBrandName() + " " + product.getProductName());
Glide.with(context)
.load(product.getProductImagePath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(crimeParentViewHolder.thumbnail);
}
#Override
public void onBindChildViewHolder(ProductChildViewHolder productChildViewHolder, int i, Object childListItem) {
final ProductVariant productVariant = (ProductVariant) childListItem;
productChildViewHolder.mCrimeDateText.setText(productVariant.getVariantName());
productChildViewHolder.variantMrp.setText(context.getString(R.string.positive_amount, productVariant.getMRP()));
productChildViewHolder.variantMrp.setPaintFlags(productChildViewHolder.variantMrp.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
productChildViewHolder.variantSellPrice.setText(context.getString(R.string.positive_amount, productVariant.getSellPrice()));
//productChildViewHolder.variantMrp.setText(productVariant.getMRP().toString());
//productChildViewHolder.variantSellPrice.setText(productVariant.getSellPrice().toString());
if (productVariant.getInCart() == 0) {
productChildViewHolder.btnProductDetailAddToCart.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailMinus.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailQty.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailPlus.setVisibility(View.GONE);
} else {
productChildViewHolder.btnProductDetailAddToCart.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailMinus.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailQty.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailPlus.setVisibility(View.VISIBLE);
}
int quantity = productVariant.getInCart();
productChildViewHolder.btnProductDetailQty.setText(Integer.toString(quantity));
productChildViewHolder.btnProductDetailAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(1);
//Utility.loadShoppingCartItems();
notifyDataSetChanged();
invalidateOptionsMenu();
//holder.db.addItem(new CartItem(1, productVariant.getProductID(), productVariant.getVariantID(), 1));
}
});
productChildViewHolder.btnProductDetailPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(1 + productVariant.getInCart());
notifyDataSetChanged();
invalidateOptionsMenu();
//if (productVariant.getInCart() > 0) {
//int count = holder.db.updateSingleRow(productVariant.getProductID(), productVariant.getVariantID(), productVariant.getInCart());
//}
}
});
productChildViewHolder.btnProductDetailMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(productVariant.getInCart() - 1);
notifyDataSetChanged();
invalidateOptionsMenu();
if (productVariant.getInCart() == 0) {
//int count = holder.db.deleteSingleRow(productVariant.getProductID(), productVariant.getVariantID());
} else if (productVariant.getInCart() > 0) {
//int count = holder.db.updateSingleRow(productVariant.getProductID(), productVariant.getVariantID(), productVariant.getInCart());
}
//Utility.displayToast(holder.db.getItemsCount() + "");
}
});
//crimeChildViewHolder.mCrimeSolvedCheckBox.setChecked(productVariant.isSolved());
}
public class ProductParentViewHolder extends ParentViewHolder {
private static final float INITIAL_POSITION = 0.0f;
private static final float ROTATED_POSITION = 180f;
private final boolean HONEYCOMB_AND_ABOVE = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
public TextView productName;
public ImageView thumbnail;
public ImageButton mParentDropDownArrow;
public ProductParentViewHolder(View itemView) {
super(itemView);
productName = (TextView) itemView.findViewById(R.id.productName);
thumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
// mParentDropDownArrow = (ImageButton) itemView.findViewById(R.id.parent_list_item_expand_arrow);
}
#SuppressLint("NewApi")
#Override
public void setExpanded(boolean expanded) {
super.setExpanded(expanded);
if (!HONEYCOMB_AND_ABOVE) {
return;
}
if (expanded) {
// mParentDropDownArrow.setRotation(ROTATED_POSITION);
} else {
// mParentDropDownArrow.setRotation(INITIAL_POSITION);
}
}
}
public class ProductChildViewHolder extends ChildViewHolder {
public TextView mCrimeDateText;
public TextView variantMrp;
public TextView variantSellPrice;
public Button btnProductDetailAddToCart, btnProductDetailPlus, btnProductDetailMinus;
public TextView btnProductDetailQty;
public ProductChildViewHolder(View itemView) {
super(itemView);
mCrimeDateText = (TextView) itemView.findViewById(R.id.variantName);
variantMrp = (TextView) itemView.findViewById(R.id.productVariantMrp);
variantSellPrice = (TextView) itemView.findViewById(R.id.productVariantSellPrice);
btnProductDetailAddToCart = (Button) itemView.findViewById(R.id.btnProductDetailAddToCart);
btnProductDetailPlus = (Button) itemView.findViewById(R.id.btnProductDetailPlus);
btnProductDetailMinus = (Button) itemView.findViewById(R.id.btnProductDetailMinus);
btnProductDetailQty = (TextView) itemView.findViewById(R.id.btnProductDetailQty);
}
}
}
When i am bottom of the page and click on item it expands, but exapnded child item doesn't shows to user because it is bottom in the screen.
I want to move that item up in the screen and show expanded items to user.
How can i do that?
You can simply use the method setSelectedGroup()
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
expandableListView.setSelectedGroup(groupPosition);
return true;
}
});
This will move the selected group to the top
EDIT
Finally I came out with a solution for your ExpandableRecyclerAdapter also. Simply put this method inside your adapter implementation. Also you will require the reference of the recyclerView inside the adapter which you can pass to the adapter at the time of initialization.
int lastPos = -1;
#Override
public void onParentListItemExpanded(int position) {
List<? extends ParentListItem> parentItemList = this.getParentItemList();
collapseAllParents();
int finalPos = position;
if (lastPos != -1 && lastPos < position) {
finalPos = position - parentItemList.get(lastPos).getChildItemList().size();
}
expandParent(finalPos);
mRecyclerView.smoothScrollToPosition(finalPos);
lastPos = position;
}
I found this issue at https://github.com/bignerdranch/expandable-recycler-view/issues/156 . Although the solution given there didn't work. Slight tweaking to that make it work.
Use this following code in your expandable listview click listener. Do something liket his
yourExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean onGroupClick(final ExpandableListView parent, View v, final int groupPosition, long id) {
....
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
parent.smoothScrollToPositionFromTop(groupPosition + 1, 0);
}
},100);
....
return true;
}
});
Use AnimatedExpandableListView

finding difficulty in setting expandable listView settin OnClick listener

I have created an expandable listview using recyclerView. I am unable to get the correct items in the recyclerView, the item at position 1 an 5 respond to same clicklistener.
ExpandableRecyclerAdapter.java
protected Context mContext;
protected List<T> allItems = new ArrayList<>();
protected List<T> visibleItems = new ArrayList<>();
private List<Integer> indexList = new ArrayList<>();
private SparseIntArray expandMap = new SparseIntArray();
private int mode;
protected static final int TYPE_HEADER = 1000;
private static final int ARROW_ROTATION_DURATION = 150;
public static final int MODE_NORMAL = 0;
public static final int MODE_ACCORDION = 1;
public ExpandableRecyclerAdapter(Context context) {
mContext = context;
}
public static class ListItem
{
public int ItemType;
public ListItem(int itemType)
{
ItemType = itemType;
}
}
#Override
public long getItemId(int i)
{
return i;
}
#Override
public int getItemCount()
{
return visibleItems == null ? 0 : visibleItems.size();
}
protected View inflate(int resourceID, ViewGroup viewGroup)
{
return LayoutInflater.from(mContext).inflate(resourceID, viewGroup, false);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View view) {
super(view);
}
}
public class HeaderViewHolder extends ViewHolder {
ImageView arrow;
public HeaderViewHolder(View view, final ImageView arrow) {
super(view);
this.arrow = arrow;
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleClick();
}
});
}
protected void handleClick() {
if (toggleExpandedItems(getLayoutPosition(), false)) {
openArrow(arrow);
} else {
closeArrow(arrow);
}
}
public void bind(int position) {
arrow.setRotation(isExpanded(position) ? 90 : 0);
}
}
public boolean toggleExpandedItems(int position, boolean notify) {
if (isExpanded(position)) {
collapseItems(position, notify);
return false;
} else
{
expandItems(position, notify);
if (mode == MODE_ACCORDION)
{
collapseAllExcept(position);
}
return true;
}
}
public void expandItems(int position, boolean notify)
{
int count = 0;
int index = indexList.get(position);
int insert = position;
for (int i=index+1; i<allItems.size() && allItems.get(i).ItemType != TYPE_HEADER; i++)
{
insert++;
count++;
visibleItems.add(insert, allItems.get(i));
indexList.add(insert, i);
}
notifyItemRangeInserted(position + 1, count);
int allItemsPosition = indexList.get(position);
expandMap.put(allItemsPosition, 1);
if (notify)
{
notifyItemChanged(position);
}
}
public void collapseItems(int position, boolean notify)
{
int count = 0;
int index = indexList.get(position);
for (int i=index+1; i<allItems.size() && allItems.get(i).ItemType != TYPE_HEADER; i++) {
count++;
visibleItems.remove(position + 1);
indexList.remove(position + 1);
}
notifyItemRangeRemoved(position + 1, count);
int allItemsPosition = indexList.get(position);
expandMap.delete(allItemsPosition);
if (notify)
{
notifyItemChanged(position);
}
}
public class StaticViewHolder extends ViewHolder {
public StaticViewHolder(View view) {
super(view);
}
}
public class ItemViewHolder extends ViewHolder {
public ItemViewHolder(View view) {
super(view);
}
}
protected boolean isExpanded(int position) {
int allItemsPosition = indexList.get(position);
return expandMap.get(allItemsPosition, -1) >= 0;
}
#Override
public int getItemViewType(int position) {
return visibleItems.get(position).ItemType;
}
public void setItems(List<T> items) {
allItems = items;
List<T> visibleItems = new ArrayList<>();
expandMap.clear();
indexList.clear();
for (int i=0; i<items.size(); i++) {
if (items.get(i).ItemType == TYPE_HEADER) {
indexList.add(i);
visibleItems.add(items.get(i));
}
}
this.visibleItems = visibleItems;
notifyDataSetChanged();
}
protected void notifyItemInserted(int allItemsPosition, int visiblePosition) {
incrementIndexList(allItemsPosition, visiblePosition, 1);
incrementExpandMapAfter(allItemsPosition, 1);
if (visiblePosition >= 0) {
notifyItemInserted(visiblePosition);
}
}
protected void removeItemAt(int visiblePosition) {
int allItemsPosition = indexList.get(visiblePosition);
allItems.remove(allItemsPosition);
visibleItems.remove(visiblePosition);
incrementIndexList(allItemsPosition, visiblePosition, -1);
incrementExpandMapAfter(allItemsPosition, -1);
notifyItemRemoved(visiblePosition);
}
private void incrementExpandMapAfter(int position, int direction) {
SparseIntArray newExpandMap = new SparseIntArray();
for (int i=0; i<expandMap.size(); i++) {
int index = expandMap.keyAt(i);
newExpandMap.put(index < position ? index : index + direction, 1);
}
expandMap = newExpandMap;
}
private void incrementIndexList(int allItemsPosition, int visiblePosition, int direction) {
List<Integer> newIndexList = new ArrayList<>();
for (int i=0; i<indexList.size(); i++) {
if (i == visiblePosition) {
if (direction > 0) {
newIndexList.add(allItemsPosition);
}
}
int val = indexList.get(i);
newIndexList.add(val < allItemsPosition ? val : val + direction);
}
indexList = newIndexList;
}
public void collapseAll() {
collapseAllExcept(-1);
}
public void collapseAllExcept(int position) {
for (int i=visibleItems.size()-1; i>=0; i--) {
if (i != position && getItemViewType(i) == TYPE_HEADER) {
if (isExpanded(i)) {
collapseItems(i, true);
}
}
}
}
public void expandAll() {
for (int i=visibleItems.size()-1; i>=0; i--) {
if (getItemViewType(i) == TYPE_HEADER) {
if (!isExpanded(i))
{
expandItems(i, true);
}
}
}
}
public static void openArrow(View view) {
view.animate().setDuration(ARROW_ROTATION_DURATION).rotation(90);
}
public static void closeArrow(View view) {
view.animate().setDuration(ARROW_ROTATION_DURATION).rotation(0);
}
public int getMode() {
return mode;
}
public void setMode(int mode) {
this.mode = mode;
}
PeopleAdapter.java
public static final int TYPE_PERSON = 1001;
static Activity context;
public PeopleAdapter(Context context) {
super(context);
PeopleAdapter.context = (Activity) context;
setItems(getSampleItems());
}
public static class PeopleListItem extends ExpandableRecyclerAdapter.ListItem {
public String Text;
public PeopleListItem(String group) {
super(TYPE_HEADER);
Text = group;
}
public PeopleListItem(String first, String last) {
super(TYPE_PERSON);
Text = first + " " + last;
}
}
public class HeaderViewHolder extends ExpandableRecyclerAdapter.HeaderViewHolder {
TextView name;
public HeaderViewHolder(View view) {
super(view, (ImageView) view.findViewById(R.id.item_arrow));
name = (TextView) view.findViewById(R.id.item_header_name);
}
public void bind(int position) {
super.bind(position);
name.setText(visibleItems.get(position).Text);
}
}
public class PersonViewHolder extends ExpandableRecyclerAdapter.ViewHolder {
TextView name;
public PersonViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.item_name);
}
public void bind(int position) {
name.setText(visibleItems.get(position).Text);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case TYPE_HEADER:
return new HeaderViewHolder(inflate(R.layout.item_header, parent));
case TYPE_PERSON:
default:
return new PersonViewHolder(inflate(R.layout.item_person, parent));
}
}
#Override
public void onBindViewHolder(ExpandableRecyclerAdapter.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case TYPE_HEADER:
((HeaderViewHolder) holder).bind(position);
break;
case TYPE_PERSON:
default:
((PersonViewHolder) holder).bind(position);
break;
}
}
private List<PeopleListItem> getSampleItems() {
List<PeopleListItem> items = new ArrayList<>();
items.add(new PeopleListItem("Friends"));
items.add(new PeopleListItem("Bill", "Smith"));
items.add(new PeopleListItem("John", "Doe"));
items.add(new PeopleListItem("Frank", "Hall"));
items.add(new PeopleListItem("Sue", "West"));
items.add(new PeopleListItem("Family"));
items.add(new PeopleListItem("Drew", "Smith"));
items.add(new PeopleListItem("Chris", "Doe"));
items.add(new PeopleListItem("Alex", "Hall"));
items.add(new PeopleListItem("Alex", "Hall"));
items.add(new PeopleListItem("Alex", "Hall"));
items.add(new PeopleListItem("Associates"));
items.add(new PeopleListItem("John", "Jones"));
items.add(new PeopleListItem("Ed", "Smith"));
items.add(new PeopleListItem("Jane", "Hall"));
items.add(new PeopleListItem("Tim", "Lake"));
items.add(new PeopleListItem("Colleagues"));
items.add(new PeopleListItem("Carol", "Jones"));
items.add(new PeopleListItem("Alex", "Smith"));
items.add(new PeopleListItem("Kristin", "Hall"));
items.add(new PeopleListItem("Pete", "Lake"));
return items;
}
i have also created a recyclerView clicklistener
MainActivity.java
recycler.setLayoutManager(new LinearLayoutManager(this));
recycler.addOnItemTouchListener(
new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// TODO Handle item click
Log.e("#####", "" + position);
switch (position)
{
case 0:
recycler.getFocusedChild();
Toast.makeText(getApplicationContext(), (CharSequence) recycler.getFocusedChild(),
Toast.LENGTH_SHORT).show();
break;
case 2:
Intent in=new Intent(getApplicationContext(),sample.class);
startActivity(in);
break;
case 7:
Toast.makeText(getApplicationContext(),"7",Toast.LENGTH_SHORT).show();
break;
}
}
})
);
recycler.setAdapter(adapter);
Expand you're bind method with a setOnClickListener.
public void bind(int position) {
name.setText(visibleItems.get(position).Text);
name.setOnClickListener(new View.OnClickListener()
#Override
public void onClick(View v) {
doSomething(visibleItems.get(position));
}
});
}

How to update data in RecylerView adapter

I have a recyclerview adapter in which each view has a button. I want to implement a fuc=nctionality such that if I click button on any view all the views of the recyclerview should be updated. How this can be achieved ?
This is what I have done in onBindViewHolder
public class StoryItemAdapter extends RecyclerView.Adapter<StoryItemAdapter.ViewHolder> {
LayoutInflater inflater;
Context context;
Bitmap bm;
ImageLoader imloader;
static ArrayList<StoryDetails> stories;
OnItemClickListener mItemClickListener;
public StoryItemAdapter(Context context,ArrayList<StoryDetails> stories) {
this.context = context;
this.stories = stories;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imloader = ImageLoader.getInstance();
imloader.init(ImageLoaderConfiguration.createDefault(context));
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getItemCount() {
return stories != null ? stories.size() : 0;
}
#SuppressWarnings("deprecation")
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(stories.get(position).getType()==null) {
holder.user_handle.setText(stories.get(position).getUsername() + "( " + stories.get(position).getHandle() + " )");
File file = imloader.getDiscCache().get(stories.get(position).getImage());
if (!file.exists()) {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheOnDisc()
.build();
imloader.displayImage(stories.get(position).getImage(), holder.image, options);
} else {
holder.image.setImageURI(Uri.parse(file.getAbsolutePath()));
}
holder.about.setText(stories.get(position).getAbout());
holder.followers.setText("Followers\n\r" + stories.get(position).getFollowers());
holder.following.setText("Following\n\r" + stories.get(position).getFollowing());
}
else
{
holder.user_handle.setText(stories.get(position).getTitle());
File file = imloader.getDiscCache().get(stories.get(position).getSi());
if (!file.exists()) {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheOnDisc()
.build();
imloader.displayImage(stories.get(position).getSi(), holder.image, options);
} else {
holder.image.setImageURI(Uri.parse(file.getAbsolutePath()));
}
holder.about.setText(stories.get(position).getDescription());
holder.followers.setText("Likes \n\r" + stories.get(position).getLikes_count());
holder.following.setText("Comments \n\r" + stories.get(position).getComment_count());
}
if(stories.get(position).getIs_following())
{
holder.follow.setText("Following");
}
else
holder.follow.setText("Follow");
final int p = position;
final ViewHolder h = holder;
holder.follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(stories.get(p).getIs_following())
{
stories.get(p).setIs_following(false);
h.follow.setText("Follow");
}
else {
stories.get(p).setIs_following(true);
h.follow.setText("Following");
}
for(int i =0;i <stories.size();i++) {
if (stories.get(p).getDb() != null) {
if(stories.get(p).getDb().equals(stories.get(i).getId()))
{
stories.get(p).setIs_following(stories.get(i).getIs_following());
}
}
}
}
});
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.story_adapter, viewGroup,
false);
return new ViewHolder(itemView);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView image;
TextView user_handle, about, followers,following,userSince;
Button follow;
public ViewHolder(View itemView) {
super(itemView);
user_handle = (TextView) itemView.findViewById(R.id.user_handle);
about = (TextView) itemView.findViewById(R.id.about);
followers = (TextView) itemView.findViewById(R.id.followers);
following = (TextView) itemView.findViewById(R.id.following);
// userSince = (TextView) itemView.findViewById(R.id.user_since);
image = (ImageView) itemView.findViewById(R.id.user_image);
follow =(Button) itemView.findViewById(R.id.follow);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
image.setLayoutParams(rlp);
image.setAdjustViewBounds(true);
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(v, getPosition());
}
}
}
public interface OnItemClickListener {
public void onItemClick(View view , int position);
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
}
You need to notify the Adapter about any dataset changed.
Try this..
holder.follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(stories.get(p).getIs_following())
{
stories.get(p).setIs_following(false);
h.follow.setText("Follow");
}
else {
stories.get(p).setIs_following(true);
h.follow.setText("Following");
}
for(int i =0;i <stories.size();i++) {
if (stories.get(p).getDb() != null) {
if(stories.get(p).getDb().equals(stories.get(i).getId()))
{
stories.get(p).setIs_following(stories.get(i).getIs_following());
}
}
}
notifyDataSetChanged();
}

Categories

Resources