I want to scroll recyclerview by click on category position of another recyclerview which is called in popup menu...Below is my code, I am using Sectional Recyclerview and i want to get section item position while click on second recyclerview item...Please note that both recyclerview item's category id is same;
CategoryMenuRecyclerview Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<MenuItem.ProductCategory> mDataset;
private ItemListner itemListner;
RestaurantMenuActivity mContext;
public MyAdapter(RestaurantMenuActivity mContext, ArrayList<MenuItem.ProductCategory> productList, ItemListner itemListner) {
mDataset = productList;
this.itemListner = itemListner;
this.mContext = mContext;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mainView;
TextView tvCategory, tvCategoryNo;
public ViewHolder(View v) {
super(v);
mainView = v;
tvCategory = (TextView) v.findViewById(R.id.tvCategory);
tvCategoryNo = (TextView) v.findViewById(R.id.tvCategoryNo);
}
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.tvCategory.setText(mDataset.get(position).getCategoryName());
holder.mainView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemListner.Item(position);
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
and i want to scroll below adapter with click item of upper recyclerview item;
RestaurantMenuAdapter;
public class RestaurantMenuAdapter extends SectionedRecyclerViewAdapter<RecyclerView.ViewHolder> {
private List<MenuItem.ProductCategory> allData;
public RestaurantMenuAdapter(List<MenuItem.ProductCategory> data) {
this.allData = data;
}
#Override
public int getSectionCount() {
return allData == null ? 0 : allData.size();
}
private MenuItem.ProductCategory getItem(int position) {
return allData.get(position);
}
#Override
public int getItemCount(int section) {
return allData.get(section).getProductDetails() == null ? 0 : allData.get(section).getProductDetails().size();
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int section) {
String sectionName = allData.get(section).getCategoryName();
SectionViewHolder sectionViewHolder = (SectionViewHolder) holder;
sectionViewHolder.tvCategory.setText(sectionName);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int section, final int relativePosition, int absolutePosition) {
final ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
itemViewHolder.tvProductName.setText(allData.get(section).getProductDetails().get(relativePosition).getProductName());
itemViewHolder.tvDescription.setText("Grass Fed Beef with creespy bacon, tasty cheese, salad, relish and hot");
itemViewHolder.tvPrice.setText("$ " + allData.get(section).getProductDetails().get(relativePosition).getCurrentPrice());
if (near_by_restaurant) {
rlAddCart.setVisibility(View.VISIBLE);
if (tvCategoryCount.getText().toString().matches("0")) {
rlAddCart.setVisibility(View.GONE);
} else {
rlAddCart.setVisibility(View.VISIBLE);
}
if (allData.get(section).getProductDetails().get(relativePosition).getIsOpen().equalsIgnoreCase("1")) {
itemViewHolder.ll_product.setAlpha(0.5f);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry kitchen is closed")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
});
} else if (allData.get(section).getProductDetails().get(relativePosition).getIsSoldout().equalsIgnoreCase("1")) {
itemViewHolder.tvSoldOut.setVisibility(View.VISIBLE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry all items are sold out")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your code
dialog.dismiss();
}
})
.show();
}
});
} else {
itemViewHolder.tvSoldOut.setVisibility(View.GONE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedPref = getSharedPreferences("cartitems", 0);
String strJson = sharedPref.getString("cartdata", "0");
try {
mainjsonArray = new JSONArray(strJson);
} catch (JSONException e) {
e.printStackTrace();
}
Intent i = new Intent(RestaurantMenuActivity.this, ProductCartActivity.class);
i.putExtra("product_id", allData.get(section).getProductDetails().get(relativePosition).getProductID());
i.putExtra("productCart", true);
i.putExtra("product_name", allData.get(section).getProductDetails().get(relativePosition).getProductName());
i.putExtra("product_price", allData.get(section).getProductDetails().get(relativePosition).getCurrentPrice());
try {
i.putExtra("jsonArray", mainjsonArray.toString());
} catch (Exception e) {
e.printStackTrace();
}
startActivityForResult(i, PRODUCT_CART);
}
});
}
} else {
rlAddCart.setVisibility(View.GONE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry you are not in restaurant")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your code
dialog.dismiss();
}
})
.show();
}
});
}
if (allData.get(section).getProductDetails().get(relativePosition).getFavorited() == 0) {
itemViewHolder.ivFav.setImageResource(R.drawable.fav_02);
} else {
itemViewHolder.ivFav.setImageResource(R.drawable.favroite_highlited);
}
itemViewHolder.ivFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ProgressDialog pd = ProgressDialog.show(RestaurantMenuActivity.this, "", "Loading...");
JSONObject postdata = new JSONObject();
try {
YupITApplication.getJsonWithHTTPPost(RestaurantMenuActivity.this, 1, new ServiceCallBack() {
#Override
public void serviceCallback(int id, JSONObject jsonResult) {
pd.dismiss();
try {
if (jsonResult.has("Data") && !jsonResult.getString("Data").equals("")) {
// {"Status":"Success","StatusCode":"200","Message":"Item Favourited!","Data":[]}
if (jsonResult.getString("Message").equalsIgnoreCase("Item Favourited!")) {
itemViewHolder.ivFav.setImageResource(R.drawable.favroite_highlited);
} else {
itemViewHolder.ivFav.setImageResource(R.drawable.fav_02);
}
Toast.makeText(getApplicationContext(), jsonResult.getString("Message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, Utils.insertfavoriteitem + "&productid=" + allData.get(section).getProductDetails().get(relativePosition).getProductID() + "&userid=" + customer_id, postdata);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Glide.with(RestaurantMenuActivity.this).load(allData.get(section).getProductDetails().get(relativePosition).getPhotoImagePath())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(itemViewHolder.ivMenu);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, boolean header) {
View v = null;
if (header) {
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_section, parent, false);
v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
width = v.getMeasuredWidth();
height = v.getMeasuredHeight();
return new SectionViewHolder(v);
} else {
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ItemViewHolder(v);
}
}
// SectionViewHolder Class for Sections
public class SectionViewHolder extends RecyclerView.ViewHolder {
final TextView tvCategory;
public SectionViewHolder(View itemView) {
super(itemView);
tvCategory = (TextView) itemView.findViewById(R.id.tvCategory);
}
}
// ItemViewHolder Class for Items in each Section
public class ItemViewHolder extends RecyclerView.ViewHolder {
final TextView tvProductName, tvDescription, tvPrice, tvSoldOut;
LinearLayout ll_product;
ImageView ivMenu, ivFav;
public ItemViewHolder(View itemView) {
super(itemView);
tvProductName = (TextView) itemView.findViewById(R.id.tvProductName);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
ivMenu = (ImageView) itemView.findViewById(R.id.ivMenu);
ll_product = (LinearLayout) itemView.findViewById(R.id.ll_product);
tvSoldOut = (TextView) itemView.findViewById(R.id.tvSoldOut);
ivFav = (ImageView) itemView.findViewById(R.id.ivFav);
}
}
public int isSectionHeaderPosition(int position) {
return Integer.parseInt(allData.get(position).getCategoryID());
}
}
Please help
i think that the position of category in popup menu will be the same as section value of the second recyclerView if you get the position of clicked item in your activity by listening on item's click you can scroll the recyclerView using the LayoutManager.
recyclerView.getLayoutManager().scrollToPosition(youPositionInTheAdapter).
Related
I have Recycler view in app I use recycler view in navigation drawer means fragment
when reyclerview is empty and when I add item in recycler view that not show but after I refresh fragment and after I add item then is showing immediately but not show first time why. I am stuck.
here is my code-:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.activity_consultant_note_fragment, container, false);
mSp = getActivity().getSharedPreferences(Constant.PREF, Context.MODE_PRIVATE);
consulatantnoterecyclerView = v.findViewById(R.id.consulatantnote_display_recycler);
swipeRefreshLayout = v.findViewById(R.id.swipeContainer);
nodatafound = v.findViewById(R.id.nodatafound);
// GetConsulatantNote();
RecyclerView.LayoutManager manager = new LinearLayoutManager(getActivity());
consulatantnoterecyclerView.setLayoutManager(manager);
consulatantnoterecyclerView.setItemAnimator(new DefaultItemAnimator());
return v;
}
void GetConsulatantNote() {
dialog = new ProgressDialog(getActivity());
dialog.show();
if (!Utils.isInternetAvailable(getActivity(), true))
return;
final ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
ConsultantNote request = new ConsultantNote();
request.setActionBy(Integer.valueOf(mSp.getString(Constant.ActionBy, "")));
request.setInPatientID(Integer.valueOf(mSp.getString(Constant.InPatientID, "")));
request.setToken(mSp.getString(Constant.TOKEN, ""));
request.setCreatedBy(Integer.valueOf(mSp.getString(Constant.MasterUserID, "")));
request.setIsActive(1);
ServiceRequest serviceRequest = new ServiceRequest();
serviceRequest.setOppID(**);
serviceRequest.setParameters(request);
Call<ConsultantNoteResponse> consultantNoteResponseCall = apiInterface.SaveConsulatantNote(serviceRequest);
consultantNoteResponseCall.enqueue(new Callback<ConsultantNoteResponse>() {
#Override
public void onResponse(Call<ConsultantNoteResponse> call, Response<ConsultantNoteResponse> response) {
if (response.body().getSuccess() == true && response.body().getValidated() == false) {
if (!response.body().getValidationErrors().isEmpty()) {
Nodatafound = true;
List<ValidationError> validationErrors = response.body().getValidationErrors();
for (int i = 0; i < validationErrors.size(); i++) {
ValidationError error = new ValidationError();
error.setErrorMessage(validationErrors.get(i).getErrorMessage());
Log.d("error", "" + validationErrors.get(i).getErrorMessage());
}
// Toast.makeText(DoctorCollection.this, "Records not found for opd", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
if (response.body().getSuccess() == true && response.body().getValidated() == true) {
//data
consultantNotes = new ArrayList<>();
consultantNotes.clear();
List<ConsultantNote> notes = response.body().getConsultantNotes();
consulatantnoterecyclerView.setVisibility(View.VISIBLE);
nodatafound.setVisibility(View.GONE);
for (int i = 0; i < notes.size(); i++) {
ConsultantNote note = new ConsultantNote();
note.setCreatedByUserFullName(notes.get(i).getCreatedByUserFullName());
note.setConsultantNotesDateTime(notes.get(i).getConsultantNotesDateTime());
note.setPatientProgress(notes.get(i).getPatientProgress());
note.setCreatedBy(notes.get(i).getCreatedBy());
note.setInPatientConsultantNoteID(notes.get(i).getInPatientConsultantNoteID());
note.setProblemsAndInterventions(notes.get(i).getProblemsAndInterventions());
consultantNotes.add(note);
}
//consulatantnoterecyclerView.setAdapter(consultantNoteAdpater);
setAdapterData(consultantNotes);
onItemDelete();
if (dialog.isShowing()) {
dialog.dismiss();
}
}
if (Nodatafound) {
consulatantnoterecyclerView.setVisibility(View.GONE);
nodatafound.setVisibility(View.VISIBLE);
}
}
#Override
public void onFailure(Call<ConsultantNoteResponse> call, Throwable t) {
}
});
dialog.dismiss();
}
void onItemDelete() {
final ConsultantNoteAdpater noteAdpater = new ConsultantNoteAdpater(context, consultantNotes);
consulatantnoterecyclerView.setAdapter(noteAdpater);
noteAdpater.setOnItemDeleteClickListener(new ConsultantNoteAdpater.OnItemClickDeleteListener() {
#Override
public void onItemClick(final int position, final Integer NoteId) {
final AlertDialog.Builder innermsg = new AlertDialog.Builder(context);
innermsg.setMessage("Are you sure you want to delete this consultant note ?");
innermsg.setCancelable(false);
innermsg.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
consultantNotes.remove(position);
noteAdpater.notifyItemRemoved(position);
noteAdpater.notifyItemRangeChanged(position, consultantNotes.size());
DeleteConsulatantNote(NoteId);
noteAdpater.notifyDataSetChanged();
GetConsulatantNote();
}
});
innermsg.setNegativeButton("cancle", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
innermsg.show();
}
});
}
private void setAdapterData(List<ConsultantNote> data) {
if (data != null) {
ArrayList<ConsultantNote> notes = new ArrayList<>();
notes.clear();
notes.addAll(consultantNotes);
adapter = new ConsultantNoteAdpater(getActivity(), notes);
adapter.notifyItemRangeChanged(0, consultantNotes.size());
// adapter.notifyDataSetChanged();
consulatantnoterecyclerView.setAdapter(adapter);
}
}
Here is my adapter code of recyclerview-:
public class ConsultantNoteAdpater extends RecyclerView.Adapter<ConsultantNoteAdpater.holder> {
LayoutInflater layoutInflater;
Context context;
List<ConsultantNote> consultantNotes;
private SharedPreferences mSp;
public OnItemClickDeleteListener onItemClickDeleteListener;
public ConsultantNoteAdpater(Context c, List<ConsultantNote> notes) {
context = c;
consultantNotes = notes;
notifyDataSetChanged();
}
#NonNull
#Override
public holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.activity_consultant_note_adpater, parent, false);
mSp = context.getSharedPreferences(Constant.PREF, Context.MODE_PRIVATE);
return new holder(v);
}
public interface OnItemClickDeleteListener {
void onItemClick(int position, Integer NoteId);
}
public void setOnItemDeleteClickListener(OnItemClickDeleteListener onItemClickDeleteListener) {
this.onItemClickDeleteListener = onItemClickDeleteListener;
}
#Override
public void onBindViewHolder(#NonNull holder holder, final int position) {
final ConsultantNote note = consultantNotes.get(position);
holder.createdby.setText(Html.fromHtml(createdby + "" + note.getCreatedByUserFullName()));
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onItemClickDeleteListener != null) {
//get pateint consulatant note id
onItemClickDeleteListener.onItemClick(position, note.getInPatientConsultantNoteID());
}
}
});
}
#Override
public int getItemCount() {
return consultantNotes.size();
}
class holder extends RecyclerView.ViewHolder {
TextView date, createdby;
ImageView delete;
public holder(View itemView) {
super(itemView);
date = itemView.findViewById(R.id.consulatant_datetime);
createdby = itemView.findViewById(R.id.consulatant_createdby);
delete = itemView.findViewById(R.id.deleteconsultant);
}
}
}
I am using retrofit to get data from api so if any one can help!!
Thanks in advance!!!
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);
}
});
}
}
}
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
I have it clicked and it gets up to it and shows the right getText() method but the setText method is not working...
userAdapter.setOnEntryClickListener(new UserAdapter.OnEntryClickListener() {
#Override
public void onEntryClick(View view, int position) {
DatabaseUser user = dbUsersList.get(position);
TextView clickedView = (TextView) view.findViewById(R.id.userAdapterFollowBtn);
if(view == clickedView) {
if (clickedView.getText().equals("following")) {
Log.d(Constants.DEBUG, " THE CLICK VIEW IS " + clickedView.getText());
//APPLY Following
String txtFollow = "follow";
clickedView.setText(txtFollow);
if (user.getIsChanged() == 0) {
user.setIsChanged(1);
} else {
user.setIsChanged(0);
}
user.setIsType(3);
db.updateFollow(user);
userAdapter.notifyDataSetChanged();
} else {
clickedView.setText("following");
if (user.getIsChanged() == 0) {
user.setIsChanged(1);
} else {
user.setIsChanged(0);
}
user.setIsType(0);
db.updateFollow(user);
userAdapter.notifyDataSetChanged();
}
} else {
Toast.makeText(getApplicationContext(), user.getUsername() + " is selected!", Toast.LENGTH_SHORT).show();
takeToUserProfile(dbUsersList.get(position));
}
}
});
Here is the adapter class:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.MyViewHolder> {
private List<DatabaseUser> dbUsersList, followingList;
private DatabaseHelper db;
private Context context;
private Typeface typeFace, italicTypeface, boldTypeface;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView userAdapterUsername, userAdapterFollowBtn;
public ImageView userAdapterUserPicture;
public MyViewHolder(View view) {
super(view);
userAdapterUsername = (TextView) view.findViewById(R.id.userAdapterUsername);
userAdapterFollowBtn = (TextView) view.findViewById(R.id.userAdapterFollowBtn);
userAdapterUserPicture = (ImageView) view.findViewById(R.id.userAdapterUserPicture);
Log.d(Constants.DEBUG, "IN MY VIEW HOLDER");
view.setOnClickListener(this);
userAdapterFollowBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mOnEntryClickListener != null) {
Log.d(Constants.DEBUG, "IN On click");
mOnEntryClickListener.onEntryClick(v, getAdapterPosition());
}
}
}
private static OnEntryClickListener mOnEntryClickListener;
public interface OnEntryClickListener {
void onEntryClick(View view, int position);
}
public void setOnEntryClickListener(OnEntryClickListener onEntryClickListener) {
mOnEntryClickListener = onEntryClickListener;
}
public UserAdapter(Context mContext, List<DatabaseUser> usersList, List<DatabaseUser> passedFollowing, Typeface myTypeface, Typeface myTypefaceItalic, Typeface myTypefaceBold) {
context = mContext;
dbUsersList = usersList;
followingList = passedFollowing;
typeFace = myTypeface;
italicTypeface = myTypefaceItalic;
boldTypeface = myTypefaceBold;
Log.d(Constants.DEBUG, "IN MY User ADAPTER CONSTRUCTOR");
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.follow_item, parent, false);
Log.d(Constants.DEBUG, "RETURN ITEM VIEW HOLDER");
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
DatabaseUser user = dbUsersList.get(position);
holder.userAdapterUsername.setTypeface(boldTypeface);
holder.userAdapterUsername.setText(user.getUsername());
final int pos = getItemViewType(position);
//TODO Create pic link
if(containsId(dbUsersList.get(pos), followingList)) {
//Then show following
holder.userAdapterFollowBtn.setText("following");
} else {
//show follow
holder.userAdapterFollowBtn.setText("follow");
}
String userspic = dbUsersList.get(pos).getPicture();
if(userspic == null) {
//SET DEFAULT OR PUT DEFAULT IN XML AND DO NOTHING IT SHOULD SHOW DEFAULT PIC
} else {
//TODO setupUser Pic
String img1 = "http://www.hindustantimes.com/Images/popup/2015/6/kungfu2.jpg";
Picasso.with(context).load(img1).transform(new RoundedTransformation()).into(holder.userAdapterUserPicture);
}
}
#Override
public int getItemCount() {
return dbUsersList.size();
}
public static boolean containsId(DatabaseUser currentUser, List<DatabaseUser> list) {
for (DatabaseUser object : list) {
if (currentUser.getUserId().equals(object.getUserId())) {
return true;
}
}
return false;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
your dbUsersList is not updating. please check your user object in dbUsersList after notify data set change.
What ended up being the problem is that I had passed in the followingList, so I never re-called to grab the new following from the db on update. The update was happening I just had to re-grab the followingList from the db to have an updated list to check against like so in a new method that was passing the list back to the contains method.
db.grabFollowersList();
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();
}