Here is my code. I have cardviews and in some i have one pic and in some there is no pic. But after scroll up and down i get pictures in every CardView (pics from previous cardview) event if there should not be any pic at all (***.size()=0). I think the problem is here
if (mDataset.get(position).getAdv_pics().size()>0){
String pic = mDataset.get(position).getAdv_pics().get(0);
ImageView image = new ImageView(mActivity);
Log.d("!!!!", position + " http://m2.biz.ua" + holder.pic + "_small.jpg");
holder.mLayout.addView(image, 1);
Picasso.with(mActivity)
.load("http://m2.biz.ua" + pic + "_small.jpg")
.resize(100, 100)
.centerCrop()
.into(image);
}
FlatListCardAdapter.class
public class FlatListCardAdapter extends RecyclerView.Adapter<FlatListCardAdapter.ViewHolder> {
private List<Flat> mDataset;
private Activity mActivity;
private String[] currency;
private OnCardClickListener mListener;
public interface OnCardClickListener{
void getFlat(Flat flatId);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mAdvText, mAdvRooms, mAdvPrice, mAdvAddr;
public LinearLayout mLayout;
public ImageButton mCallButton;
public Button test;
public String pic;
public ImageView smallImage;
public View view;
private CardView mCardView;
public ViewHolder(View v ) {
super(v);
view=v;
mAdvText = (TextView) v.findViewById(R.id.advText);
mAdvRooms = (TextView) v.findViewById(R.id.advRooms);
mAdvPrice = (TextView) v.findViewById(R.id.advPrice);
mAdvAddr = (TextView) v.findViewById(R.id.advAddr);
mLayout = (LinearLayout) v.findViewById(R.id.picMainLayout);
mCallButton = (ImageButton) v.findViewById(R.id.callAdv);
mCardView = (CardView) v.findViewById(R.id.card_view);
}
}
public FlatListCardAdapter(Activity activity, List<Flat> dataset, OnCardClickListener mListener) {
mDataset = dataset;
mActivity = activity;
this.mListener = mListener;
}
#Override
public FlatListCardAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_realty_list_card_custom, parent, false);
ViewHolder vh = new ViewHolder(v);
currency=mActivity.getResources().getStringArray(R.array.currency);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Flat mFlat = mDataset.get(position);
String mCurrency="";
if ( Integer.parseInt(mFlat.getAdv_currency())>0 ){
mCurrency=currency[Integer.parseInt(mFlat.getAdv_currency())];
}
holder.mAdvRooms.setText(mFlat.getAdv_rooms()+" ");
holder.mAdvPrice.setText(mFlat.getAdv_price()+" "+mCurrency);
holder.mAdvText.setText(mFlat.getAdv_text());
holder.mAdvAddr.setText(mFlat.getAdv_addr());
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("!!!!", mFlat.getId());
try {
mListener = (MainActivity) mActivity;
mListener.getFlat(mFlat);
} catch (ClassCastException e) {
throw new ClassCastException(mActivity.toString() + " must implement OnArticleSelectedListener");
}
}
});
holder.mCallButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
List<String> phone = mFlat.getAdv_phone();
if (phone.size()>0) {
Toast.makeText(mActivity, phone.get(0), Toast.LENGTH_SHORT).show();
}
}
});
Log.d("!!!!", "SIZE: " +mDataset.get(position).getAdv_pics().size());
if (mDataset.get(position).getAdv_pics().size()>0){
String pic = mDataset.get(position).getAdv_pics().get(0);
ImageView image = new ImageView(mActivity);
Log.d("!!!!", position + " http://****" + holder.pic + "_small.jpg");
holder.mLayout.addView(image, 1);
Picasso.with(mActivity)
.load("http://****" + pic + "_small.jpg")
.resize(100, 100)
.centerCrop()
.into(image);
}
/**/
}
#Override
public int getItemCount() {
if (mDataset==null){
return 0;
}
return mDataset.size();
}
}
Item view is reused in the RecyclerView. The issue is here
if (mDataset.get(position).getAdv_pics().size()>0){
...
}
add else clause and set image as null there. As is shown in the code below
if (mDataset.get(position).getAdv_pics().size()>0){
...
}else{
image.setImageBitmap(null);
}
Related
Create an adapter object, find recycler view id to set adapter and then set layout manager. In scroll listener, unable to get correct LastVisibleItemPosition, it return -1 to me. findFirstVisibleItemPosition() also returning -1.
//Here is Adapter
public class CategoryProduct extends RecyclerView.Adapter<RecyclerView.ViewHolder>
`enter code here`{
private static final int ITEM = 0;
private static final int LOADING = 1;
public String vertical = "";
Context context;
private boolean isLoadingAdded = false;
private boolean retryPageLoad = false;
private List<com.example.it.camanagement.model.CategoryProduct> dataSet;
public CategoryProduct(ArrayList<com.example.it.camanagement.model.CategoryProduct> data, Context context, String vertical) {
this.dataSet = data;
this.context = context;
this.vertical = vertical;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case ITEM:
View viewLoading;
if (vertical.equals("vertical")) {
viewLoading = LayoutInflater.from(parent.getContext())
.inflate(R.layout.category_product_list, parent, false);
} else {
viewLoading = LayoutInflater.from(parent.getContext())
.inflate(R.layout.category_product_list_grid, parent, false);
}
viewHolder = new MyViewHolder(viewLoading);
break;
case LOADING:
View viewLoading1 = inflater.inflate(R.layout.item_progress, parent, false);
viewHolder = new LoadingVH(viewLoading1);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int listPosition) {
if (listPosition == dataSet.size() - 1) {
CategoryDetails categoryDetails = (CategoryDetails) context;
categoryDetails.onBottomReached(listPosition);
}
switch (getItemViewType(listPosition)) {
case ITEM:
final MyViewHolder myViewHolder = (MyViewHolder) holder;
TextView textViewName = myViewHolder.productName;
// TextView textViewVersion = holder.textViewVersion;
ImageView imageView = myViewHolder.productImage;
RatingBar productRating = myViewHolder.productRasting;
TextView productCost = myViewHolder.productCost;
TextView productDiscount = myViewHolder.productDistCount;
TextView productCOLOR = myViewHolder.productColor;
TextView productId = myViewHolder.product_id;
TextView productModel = myViewHolder.productModel;
TextView productQuantity = myViewHolder.productQuantity;
productModel.setText(dataSet.get(listPosition).getModel());
productQuantity.setText(dataSet.get(listPosition).getQuantity());
productId.setText(dataSet.get(listPosition).getProduct_id());
textViewName.setText(dataSet.get(listPosition).getName());
Glide.with(context).load(dataSet.get(listPosition).getImage()).into(imageView);
productRating.setRating(Float.parseFloat(String.valueOf(dataSet.get(listPosition).getRating())));
productCost.setText("RM " + dataSet.get(listPosition).getPrice());
productDiscount.setText(dataSet.get(listPosition).getDiscount());
if (dataSet.get(listPosition).getSpecial().trim().length() != 0) {
myViewHolder.special.setText("RM " + dataSet.get(listPosition).getSpecial());
strikeThroughText(productCost);
}
break;
case LOADING:
LoadingVH loadingVH = (LoadingVH) holder;
if (retryPageLoad) {
loadingVH.mErrorLayout.setVisibility(View.VISIBLE);
loadingVH.mProgressBar.setVisibility(View.GONE);
loadingVH.mErrorTxt.setText(
errorMsg != null ?
errorMsg :
context.getString(R.string.error_msg_unknown));
} else {
loadingVH.mErrorLayout.setVisibility(View.GONE);
loadingVH.mProgressBar.setVisibility(View.VISIBLE);
}
break;
}
}
private void strikeThroughText(TextView price) {
price.setPaintFlags(price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
#Override
public int getItemCount() {
return dataSet == null ? 0 : dataSet.size();
//return dataSet.size();
}
#Override
public int getItemViewType(int position) {
return (position == dataSet.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
}
public com.example.it.camanagement.model.CategoryProduct getItem(int position) {
return dataSet.get(position);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView productName, productColor, productCost, productDistCount, product_id, productModel, productQuantity, special;
RatingBar productRasting;
ImageView productImage;
public MyViewHolder(View itemView) {
super(itemView);
this.productName = (TextView) itemView.findViewById(R.id.product_name);
this.productColor = (TextView) itemView.findViewById(R.id.product_color);
this.productCost = (TextView) itemView.findViewById(R.id.cost);
this.productDistCount = (TextView) itemView.findViewById(R.id.discount);
this.productRasting = (RatingBar) itemView.findViewById(R.id.product_rating);
this.product_id = (TextView) itemView.findViewById(R.id.product_iid);
this.productQuantity = (TextView) itemView.findViewById(R.id.quantity);
this.productModel = (TextView) itemView.findViewById(R.id.modelProduct);
//this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
this.productImage = (ImageView) itemView.findViewById(R.id.product_image);
this.special = (TextView) itemView.findViewById(R.id.special);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent i = new Intent(context, ProductDescription.class);
i.putExtra("productName", ((TextView) v.findViewById(R.id.product_name)).getText().toString());
i.putExtra("product_id", ((TextView) v.findViewById(R.id.product_iid)).getText().toString());
context.startActivity(i);
if (getPosition() == 0) {
// Toast.makeText(v.getContext(), " On CLick one", Toast.LENGTH_SHORT).show();
}
if (getPosition() == 1) {
//Toast.makeText(v.getContext(), " On CLick Two", Toast.LENGTH_SHORT).show();
}
if (getPosition() == 2) {
// Toast.makeText(v.getContext(), " On CLick Three", Toast.LENGTH_SHORT).show();
}
if (getPosition() == 3) {//
// Toast.makeText(v.getContext(), " On CLick Fore", Toast.LENGTH_SHORT).show();
}
}
});
}
}
protected class LoadingVH extends RecyclerView.ViewHolder {
private ProgressBar mProgressBar;
private ImageButton mRetryBtn;
private TextView mErrorTxt;
private LinearLayout mErrorLayout;
public LoadingVH(View itemView) {
super(itemView);
mProgressBar = (ProgressBar) itemView.findViewById(R.id.loadmore_progress);
mRetryBtn = (ImageButton) itemView.findViewById(R.id.loadmore_retry);
mErrorTxt = (TextView) itemView.findViewById(R.id.loadmore_errortxt);
mErrorLayout = (LinearLayout) itemView.findViewById(R.id.loadmore_errorlayout);
}
}
}
//Recycler View
categoryProduct = (RecyclerView) findViewById(R.id.categoryProductList);
categoryProductAdapter = new CategoryProduct(categoryProduct,categoryProductList, context);
categoryProduct.setAdapter(categoryProductAdapter);
categoryProduct.setNestedScrollingEnabled(false);
categoryProduct.setHasFixedSize(false);
girdLayoutManager = new GridLayoutManager(CategoryDetails.this, 2);
categoryProduct.setLayoutManager(girdLayoutManager);
//scroll Listener
scrollListener = new EndlessRecyclerViewScrollListener(girdLayoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
Log.d("pageCount", "" + page);
Log.d("FirstVisibleITEM", "" + girdLayoutManager.findFirstVisibleItemPosition());
Log.d("LastVisibleITEM", "" + girdLayoutManager.findLastVisibleItemPosition());
}
};
categoryProduct.addOnScrollListener(scrollListener);
Finally solved it, Issue was: I was creating the object of layout manager two times. one in method(API response received and after notify the adapter) and another one in OnCreate() method of activity. after removing one object from method( API response received and after notify the adapter), fixed the issue.
I have implemented an recycler view with Multi Select successfully using addOnItemTouchListener for identifying and selecting using single and double click.When i have Less than 5 items int the recycler view,Everything works fine but when i have more data,to be exact when the recycler view starts recycling the view,my selection is going crazy and it selects differnt possition.I logged out to see the clicking position,those seems to be right but something is not right which makes my selection wrong.I'm new to programming and to android app development.Can anyone take alot at this and help me out please,Here is my code
My adapter class
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactHolder> implements SectionIndexer, Filterable {
public List<Contact> contactList;
List<Contact> filteredUsersList;
CustomFilter filter;
Context mContext;
int itemResource;
ArrayList<Contact> selected_usersList = new ArrayList<>();
int pos;
private ArrayList<Integer> mSectionPositions;
ContactAdapter(Context mContext, int itemResource, List<Contact> contactList, ArrayList<Contact> selectedList) {
this.contactList = contactList;
this.mContext = mContext;
this.itemResource = itemResource;
this.selected_usersList = selectedList;
this.filteredUsersList = contactList;
}
#Override
public ContactHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(itemResource, parent, false);
return new ContactHolder(v);
}
#Override
public void onBindViewHolder(final ContactHolder holder, int position) {
pos = position;
final Contact contact = contactList.get(pos);
holder.colg.setText(contact.getColg());
holder.name.setText(contact.getName());
holder.job.setText(contact.getJob());
if (contact.getImage() != null)
holder.img.setImageBitmap(Utility.getPhoto(contact.getImage()));
}
#Override
public int getItemCount() {
return this.contactList.size();
}
class ContactHolder extends RecyclerView.ViewHolder {
private TextView name, colg, job, id, mentee, mentor, participant;
private ImageView selected;
// private PorterShapeImageView img;
private HexagonMaskView img;
private RelativeLayout rr_layout;
ItemClickListener itemClickListener;
ContactHolder(View itemView) {
super(itemView);
// Set up the UI widgets of the holder
// img = (PorterShapeImageView) itemView.findViewById(R.id.contact_image);
img = (HexagonMaskView) itemView.findViewById(R.id.contact_image);
name = (TextView) itemView.findViewById(R.id.contact_name);
colg = (TextView) itemView.findViewById(R.id.contact_colg);
job = (TextView) itemView.findViewById(R.id.contact_job);
mentee = (TextView) itemView.findViewById(R.id.mentee);
mentor = (TextView) itemView.findViewById(R.id.mentor);
participant = (TextView) itemView.findViewById(R.id.participant);
rr_layout = (RelativeLayout) itemView.findViewById(R.id.rr_layout);
selected = (ImageView) itemView.findViewById(R.id.tic_contact_selected);
}
}
}
My RecyclerItemClickListener Class
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
public interface OnItemClickListener {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickListener mListener;
private GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null) {
mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
My Implementation of addOnItemTouchListener
contactsRecyclerViewT.addOnItemTouchListener(new RecyclerItemClickListener(this, contactsRecyclerViewT, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, final int position) {
Log.e("tag", "" + position);
for (int i = 0; i < multiselect_list.size(); i++) {
Log.e("tag", "sss" + multiselect_list.get(i).getName());
}
pos = position;
contact = contactArrayList.get(position);
menteeTextView = (TextView) view.findViewById(R.id.mentee);
mentorTextView = (TextView) view.findViewById(R.id.mentor);
participantTextView = (TextView) view.findViewById(R.id.participant);
rr_layout = (RelativeLayout) view.findViewById(R.id.rr_layout);
selected = (ImageView) view.findViewById(R.id.tic_contact_selected);
img = (HexagonMaskView) view.findViewById(R.id.contact_image);
name = (TextView) view.findViewById(R.id.contact_name);
if (isMultiSelect) {
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
multi_select(position);
if (multiselect_list.contains(contactArrayList.get(position))) {
contact.setStatus("0");
Log.e("tag", "setStatus" + contact.getStatus());
Log.e("tag", "position " + position);
rr_layout.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.bg_card_selected));
selected.setVisibility(View.VISIBLE);
mentorTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
participantTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
menteeTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorAccent));
menteeTextView.setVisibility(View.VISIBLE);
mentorTextView.setVisibility(View.VISIBLE);
participantTextView.setVisibility(View.VISIBLE);
menteeTextView.setClickable(true);
mentorTextView.setClickable(true);
participantTextView.setClickable(true);
} else {
rr_layout.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.cement));
selected.setVisibility(View.GONE);
Log.e("tag", "position " + position);
menteeTextView.setVisibility(View.GONE);
mentorTextView.setVisibility(View.GONE);
participantTextView.setVisibility(View.GONE);
menteeTextView.setClickable(false);
mentorTextView.setClickable(false);
participantTextView.setClickable(false);
}
}
});
mentorTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
contact.setStatus("1");
Log.e("tag", "setStatus" + contact.getStatus());
mentorTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorAccent));
menteeTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
participantTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
}
});
menteeTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
contact.setStatus("0");
Log.e("tag", "setStatus" + contact.getStatus());
mentorTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
participantTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
menteeTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorAccent));
}
});
participantTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
contact.setStatus("2");
Log.e("tag", "setStatus" + contact.getStatus());
mentorTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
menteeTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
participantTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorAccent));
}
});
name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ContactsActivity.this, OtherProfileActivity.class);
intent.putExtra("id", Integer.parseInt(contactArrayList.get(position).getId()));
startActivity(intent);
}
});
} else {
Intent intent = new Intent(ContactsActivity.this, OtherProfileActivity.class);
intent.putExtra("id", Integer.parseInt(contactArrayList.get(position).getId()));
startActivity(intent);
}
// contactList.get(position).setStatus("1");
// contactList.get(position).setStatus("0");
}
#Override
public void onItemLongClick(View view, int position) {
contact = contactArrayList.get(position);
Log.e("tag", "" + position);
for (int i = 0; i < multiselect_list.size(); i++) {
Log.e("tag", "sss" + multiselect_list.get(i).getName());
}
menteeTextView = (TextView) view.findViewById(R.id.mentee);
mentorTextView = (TextView) view.findViewById(R.id.mentor);
participantTextView = (TextView) view.findViewById(R.id.participant);
rr_layout = (RelativeLayout) view.findViewById(R.id.rr_layout);
selected = (ImageView) view.findViewById(R.id.tic_contact_selected);
img = (HexagonMaskView) view.findViewById(R.id.contact_image);
name = (TextView) view.findViewById(R.id.contact_name);
if (!isMultiSelect) {
multiselect_list = new ArrayList<>();
isMultiSelect = true;
if (mActionMode == null) {
mActionMode = startActionMode(mActionModeCallback);
}
}
multi_select(position);
if (multiselect_list.contains(contactArrayList.get(position))) {
rr_layout.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.bg_card_selected));
selected.setVisibility(View.VISIBLE);
contact.setStatus("0");
Log.e("tag", "setStatus" + contact.getStatus());
Log.e("tag", "position " + position);
mentorTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
participantTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
menteeTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorAccent));
menteeTextView.setVisibility(View.VISIBLE);
mentorTextView.setVisibility(View.VISIBLE);
participantTextView.setVisibility(View.VISIBLE);
menteeTextView.setClickable(true);
mentorTextView.setClickable(true);
participantTextView.setClickable(true);
} else {
rr_layout.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.cement));
selected.setVisibility(View.GONE);
Log.e("tag", "position " + position);
menteeTextView.setVisibility(View.GONE);
mentorTextView.setVisibility(View.GONE);
participantTextView.setVisibility(View.GONE);
menteeTextView.setClickable(false);
mentorTextView.setClickable(false);
participantTextView.setClickable(false);
}
}
}));
ArrayList<AlphabetItem> mAlphabetItems = new ArrayList<>();
List<String> strAlphabets = new ArrayList<>();
for (int i = 0; i < contactArrayList.size(); i++) {
Contact contact = contactArrayList.get(i);
String name = contact.getName();
if (name == null || name.trim().isEmpty())
continue;
String word = name.substring(0, 1);
if (!strAlphabets.contains(word)) {
strAlphabets.add(word);
mAlphabetItems.add(new AlphabetItem(i, word, false));
}
}
}
add boolena array
boolean [] itemcheck;
initialize in constructor wit your arraylist.
itemcheck = new boolean[feedItemList.size()];
check in bindview holder like this
if(itemcheck[position]==true){
holder.row_linearlayout.setBackgroundColor(Color.parseColor("#b7c5ea"));
}else {
holder.row_linearlayout.setBackgroundColor(0xFFFFFFFF);
//holder.row_linearlayout.setBackgroundResource(R.drawable.blurback);
}
and set ture or false onclick of your relativelayout controle instead of any other controle .
holder.row_linearlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout Lout = (LinearLayout) v.findViewById(R.id.selectlinear);
if(model.isSelected()){
Lout.setBackgroundColor(0xFFFFFFFF);
itemcheck[position]=false;
//get all other controle value here
}else{
Lout.setBackgroundColor(Color.parseColor("#b7c5ea"));
itemcheck[position]=true;
//get all other controle value here
}
}
});
You are doing most of the view manipulation in Onclick listener, you should move that to you adapter onBindView, because even if you set in Onclick listener, it will modify when user scroll.
I am not giving complete view manipulation, I am just giving the hint how we should do.
#Override
public void onBindViewHolder(final ContactHolder holder, int position) {
pos = position;
final Contact contact = contactList.get(pos);
holder.colg.setText(contact.getColg());
holder.name.setText(contact.getName());
holder.job.setText(contact.getJob());
if (contact.getImage() != null)
holder.img.setImageBitmap(Utility.getPhoto(contact.getImage()));
if (multiselect_list.contains(contactArrayList.get(position))) { // May be you should check form your fragment or actvity using listeners
holder.mentee.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
holder.participant.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
holder.mentee.setVisibility(View.VISIBLE);
holder.participant.setVisibility(View.VISIBLE);
} else {
holder.mentee.setVisibility(View.GONE);
holder.participant.setVisibility(View.GONE);
}
}
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();
}
I am using a cardview with recyclerview with hardcoded values such as string arrays. But now i want to add new cardview on each button click with user enter values and user select image and keep remain all cardviews on app exit.I mean to say that cardview should be added one by one only.Any solution plz guide me.
cardview Adapter class
public class CardViewDataAdapter extends RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
private static ArrayList<FeddProperties> dataSet;
private static Context context;
public CardViewDataAdapter(Context context, ArrayList<FeddProperties> os_versions) {
this.context = context;
dataSet = os_versions;
}
#Override
public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.card_view, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(CardViewDataAdapter.ViewHolder viewHolder, int i) {
FeddProperties fp = dataSet.get(i);
viewHolder.vehicleNumber.setText(fp.getTitle());
viewHolder.iconView.setImageResource(fp.getThumbnail());
viewHolder.feed = fp;
}
#Override
public int getItemCount() {
return dataSet.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView vehicleNumber;
public ImageView iconView;
public FeddProperties feed;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
vehicleNumber = (TextView) itemLayoutView
.findViewById(R.id.vehiclenumber);
iconView = (ImageView) itemLayoutView
.findViewById(R.id.iconId);
itemLayoutView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), InformingUser.class);
v.getContext().startActivity(intent);
((MainActivity) context).getSupportFragmentManager().beginTransaction().replace
(R.id.containerView, new InformingUser()).commit();
//Toast.makeText(v.getContext(), "os version is: " + feed.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
}
Java file....
private void initContrls()
{
SharedPreferences prefs = context.getSharedPreferences(MY_PREFS_NAME, 0);
vehiclecatory = prefs.getString("vehicle_category", "");
vehicletype = prefs.getString("vehicle_type", "");
String versions = prefs.getString("city", "")+" "+prefs.getString("dis", "")+" "+prefs.getString("number", "");
String vehicleCompany = prefs.getString("company", "")+" "+prefs.getString("model", "");
if(vehiclecatory.equals("1"))
{
if (vehicletype.equals("1"))
{
icons = R.drawable.contwowheel;
}
else if (vehicletype.equals("2"))
{
icons = R.drawable.comfourwheel;
}
else if (vehicletype.equals("3"))
{
icons = R.drawable.comheavy;
}
}
else if (vehiclecatory.equals("2"))
{
if (vehicletype.equals("1"))
{
icons = R.drawable.nontwowheel;
}
else if (vehicletype.equals("2"))
{
icons = R.drawable.nonfourwheel;
}
else if (vehicletype.equals("3"))
{
icons = R.drawable.nonheavy;
}
}
os_versions = new ArrayList<FeddProperties>();
for (int i = 0; i < 2; i++) {
FeddProperties feed = new FeddProperties();
feed.setTitle(versions);
feed.setVehicleCompany(vehicleCompany);
feed.setThumbnail(icons);
os_versions.add(feed);
}
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
mAdapter = new CardViewDataAdapter(context,os_versions);
recyclerView.setAdapter(mAdapter);
}
here there is an example to add cardview dinamically
In this example cardview are create with for:
for (int index = 0; index < 20; index++) {
DataObject obj = new DataObject("Some Primary Text " + index,
"Secondary " + index);
results.add(index, obj);
}
but you can inser into onClick action :)