I have a problem that I have been trying to solve for too long but I can't know what causes the problem.
I have a marks list that contains Test objects and subject strings that I use as sections between marks, I use getClass() method to determine if an object is a string or Test, if it is a string, I hide the test's RelativeLayout, if it is a test then I hide the RelativeLayout of the subject. But when scrolling, items get removed and and re-added randomly.
my adapter's class:
public class MarksAdapter extends RecyclerView.Adapter<MarksAdapter.MyHolder>{
public class MyHolder extends RecyclerView.ViewHolder{
RelativeLayout card;
TextView title;
TextView total;
View divider;
int posito;
RelativeLayout group;
TextView groupTitle;
TextView groupMark;
public MyHolder(View itemView) {
super(itemView);
this.card = (RelativeLayout)itemView.findViewById(R.id.card);
this.title = (TextView)itemView.findViewById(R.id.title);
this.total = (TextView)itemView.findViewById(R.id.mark);
this.divider = itemView.findViewById(R.id.item_divider);
this.group = (RelativeLayout)itemView.findViewById(R.id.group);
this.groupTitle = (TextView)itemView.findViewById(R.id.group_title);
this.groupMark = (TextView)itemView.findViewById(R.id.group_mark);
}
}
final ArrayList marks;
Context ctx;
String selectedSem;
TestDatabase db;
public MarksAdapter(Context c, ArrayList marks,String sem,TestDatabase db,ArrayList<Integer> sections){
this.marks = marks;
ctx = c;
selectedSem = sem;
this.db = db;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyHolder(LayoutInflater.from(ctx).inflate(R.layout.mark_child, parent, false));
}
int lastPosition = -1;
int offset = 0;
#Override
public void onBindViewHolder(final MyHolder holder, final int positioner) {
holder.posito = positioner;
if(marks.get(holder.posito).getClass() == Test.class) {
holder.group.setVisibility(View.GONE);
//mark
final Test test = (Test)marks.get(positioner);
holder.title.setText(test.getName());
holder.total.setText(String.format(ctx.getString(R.string.new_m_sum), test.getMarkGot(), test.getMarkOver()));
//add here
holder.card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx,addTest.class);
Test mark = (Test)marks.get(holder.posito);
i.putExtra("t_name",mark.getName());
i.putExtra("subject",mark.getSubject());
i.putExtra("mark_got",mark.getMarkGot());
i.putExtra("mark_over",mark.getMarkOver());
i.putExtra("mode","edit");
i.putExtra("oldId", mark.getId());
ctx.startActivity(i);
}
});
holder.card.setLongClickable(true);
holder.card.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
final Dialog dialo = new Dialog(ctx);
dialo.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialo.setContentView(R.layout.material_dialog);
TextView title = (TextView) dialo.findViewById(R.id.title);
TextView body = (TextView) dialo.findViewById(R.id.body);
Button negative = (Button) dialo.findViewById(R.id.negative);
negative.setText(ctx.getString(R.string.cancel));
Button positive = (Button) dialo.findViewById(R.id.positive);
positive.setText(ctx.getString(R.string.Delete));
title.setText(ctx.getString(R.string.d));
body.setText(ctx.getString(R.string.q_delete) + " " + test.getName() + " " + ctx.getString(R.string.de_comp));
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialo.dismiss();
}
});
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vir) {
TestDatabase tb = new TestDatabase(ctx);
SemesterDatabase semesterDatabase = new SemesterDatabase(ctx);
tb.deleteTest(holder.posito, semesterDatabase.getSelected().getName());
MarksAdapter.this.notifyItemRemoved(holder.posito);
marks.remove(holder.posito);
for (int i = 0; i < marks.size(); i++) {
if(!(marks.get(i) instanceof Test)) {
String sub = String.valueOf(marks.get(i));
if(db.isNoValue(sub,selectedSem)){
marks.remove(i);
notifyItemRemoved(i);
}
}
}
dialo.dismiss();
}
});
dialo.show();
return true;
}
});
}else {
holder.group.setVisibility(View.VISIBLE);
holder.card.setVisibility(View.GONE);
//group
if(holder.posito == 0) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)holder.group.getLayoutParams();
params.setMargins(0,0,0,0);
holder.group.setLayoutParams(params);
}
String sub = String.valueOf(marks.get(holder.posito));
holder.groupTitle.setText(sub);
holder.groupMark.setText(db.getTotalSubjectMarks(sub,selectedSem));
}
if(lastPosition < holder.posito) {
if(holder.card.getVisibility() == View.VISIBLE) {
Animation slide = AnimationUtils.loadAnimation(ctx, R.anim.marks);
slide.setInterpolator(new AccelerateInterpolator());
slide.setDuration(700);
offset += 100;
slide.setStartOffset(offset);
holder.card.startAnimation(slide);
} else {
Animation slide = AnimationUtils.loadAnimation(ctx, R.anim.mark_groups);
slide.setInterpolator(new AccelerateInterpolator());
slide.setDuration(700);
offset += 50;
slide.setStartOffset(offset);
holder.group.startAnimation(slide);
}
lastPosition = holder.posito;
}
}
#Override
public int getItemCount() {
return marks.size();
}
}
Note: I already tried the itemViewType method but it didn't work for me
Thanks in advance!
I believe you missed to set holder.card back to visible, like this
if(marks.get(holder.posito).getClass() == Test.class) {
holder.card.setVisibility(View.Visible); //add back this
holder.group.setVisibility(View.GONE);
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);
}
}
This is my ExpandableRecyclerAdapter adapter
public class MyAdapter extends ExpandableRecyclerAdapter<MyAdapter.ProductParentViewHolder, MyAdapter.ProductChildViewHolder> {
private LayoutInflater mInflater;
private Context context;
private List<? extends ParentListItem> mParentItemList;
public MyAdapter(Context context, List<ParentListItem> itemList) {
super(itemList);
mInflater = LayoutInflater.from(context);
this.context = context;
this.mParentItemList = itemList;
}
#Override
public ProductParentViewHolder onCreateParentViewHolder(ViewGroup viewGroup) {
View view = mInflater.inflate(R.layout.list_item_crime_parent, viewGroup, false);
return new ProductParentViewHolder(view);
}
#Override
public ProductChildViewHolder onCreateChildViewHolder(ViewGroup viewGroup) {
View view = mInflater.inflate(R.layout.list_item_crime_child, viewGroup, false);
return new ProductChildViewHolder(view);
}
#Override
public void onBindParentViewHolder(ProductParentViewHolder crimeParentViewHolder, int i, ParentListItem parentListItem) {
Product product = (Product) parentListItem;
crimeParentViewHolder.productName.setText(product.getBrandName() + " " + product.getProductName());
Glide.with(context)
.load(product.getProductImagePath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(crimeParentViewHolder.thumbnail);
}
#Override
public void onBindChildViewHolder(ProductChildViewHolder productChildViewHolder, int i, Object childListItem) {
final ProductVariant productVariant = (ProductVariant) childListItem;
productChildViewHolder.mCrimeDateText.setText(productVariant.getVariantName());
productChildViewHolder.variantMrp.setText(context.getString(R.string.positive_amount, productVariant.getMRP()));
productChildViewHolder.variantMrp.setPaintFlags(productChildViewHolder.variantMrp.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
productChildViewHolder.variantSellPrice.setText(context.getString(R.string.positive_amount, productVariant.getSellPrice()));
//productChildViewHolder.variantMrp.setText(productVariant.getMRP().toString());
//productChildViewHolder.variantSellPrice.setText(productVariant.getSellPrice().toString());
if (productVariant.getInCart() == 0) {
productChildViewHolder.btnProductDetailAddToCart.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailMinus.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailQty.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailPlus.setVisibility(View.GONE);
} else {
productChildViewHolder.btnProductDetailAddToCart.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailMinus.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailQty.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailPlus.setVisibility(View.VISIBLE);
}
int quantity = productVariant.getInCart();
productChildViewHolder.btnProductDetailQty.setText(Integer.toString(quantity));
productChildViewHolder.btnProductDetailAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(1);
//Utility.loadShoppingCartItems();
notifyDataSetChanged();
invalidateOptionsMenu();
//holder.db.addItem(new CartItem(1, productVariant.getProductID(), productVariant.getVariantID(), 1));
}
});
productChildViewHolder.btnProductDetailPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(1 + productVariant.getInCart());
notifyDataSetChanged();
invalidateOptionsMenu();
//if (productVariant.getInCart() > 0) {
//int count = holder.db.updateSingleRow(productVariant.getProductID(), productVariant.getVariantID(), productVariant.getInCart());
//}
}
});
productChildViewHolder.btnProductDetailMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(productVariant.getInCart() - 1);
notifyDataSetChanged();
invalidateOptionsMenu();
if (productVariant.getInCart() == 0) {
//int count = holder.db.deleteSingleRow(productVariant.getProductID(), productVariant.getVariantID());
} else if (productVariant.getInCart() > 0) {
//int count = holder.db.updateSingleRow(productVariant.getProductID(), productVariant.getVariantID(), productVariant.getInCart());
}
//Utility.displayToast(holder.db.getItemsCount() + "");
}
});
//crimeChildViewHolder.mCrimeSolvedCheckBox.setChecked(productVariant.isSolved());
}
public class ProductParentViewHolder extends ParentViewHolder {
private static final float INITIAL_POSITION = 0.0f;
private static final float ROTATED_POSITION = 180f;
private final boolean HONEYCOMB_AND_ABOVE = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
public TextView productName;
public ImageView thumbnail;
public ImageButton mParentDropDownArrow;
public ProductParentViewHolder(View itemView) {
super(itemView);
productName = (TextView) itemView.findViewById(R.id.productName);
thumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
// mParentDropDownArrow = (ImageButton) itemView.findViewById(R.id.parent_list_item_expand_arrow);
}
#SuppressLint("NewApi")
#Override
public void setExpanded(boolean expanded) {
super.setExpanded(expanded);
if (!HONEYCOMB_AND_ABOVE) {
return;
}
if (expanded) {
// mParentDropDownArrow.setRotation(ROTATED_POSITION);
} else {
// mParentDropDownArrow.setRotation(INITIAL_POSITION);
}
}
}
public class ProductChildViewHolder extends ChildViewHolder {
public TextView mCrimeDateText;
public TextView variantMrp;
public TextView variantSellPrice;
public Button btnProductDetailAddToCart, btnProductDetailPlus, btnProductDetailMinus;
public TextView btnProductDetailQty;
public ProductChildViewHolder(View itemView) {
super(itemView);
mCrimeDateText = (TextView) itemView.findViewById(R.id.variantName);
variantMrp = (TextView) itemView.findViewById(R.id.productVariantMrp);
variantSellPrice = (TextView) itemView.findViewById(R.id.productVariantSellPrice);
btnProductDetailAddToCart = (Button) itemView.findViewById(R.id.btnProductDetailAddToCart);
btnProductDetailPlus = (Button) itemView.findViewById(R.id.btnProductDetailPlus);
btnProductDetailMinus = (Button) itemView.findViewById(R.id.btnProductDetailMinus);
btnProductDetailQty = (TextView) itemView.findViewById(R.id.btnProductDetailQty);
}
}
}
When i am bottom of the page and click on item it expands, but exapnded child item doesn't shows to user because it is bottom in the screen.
I want to move that item up in the screen and show expanded items to user.
How can i do that?
You can simply use the method setSelectedGroup()
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
expandableListView.setSelectedGroup(groupPosition);
return true;
}
});
This will move the selected group to the top
EDIT
Finally I came out with a solution for your ExpandableRecyclerAdapter also. Simply put this method inside your adapter implementation. Also you will require the reference of the recyclerView inside the adapter which you can pass to the adapter at the time of initialization.
int lastPos = -1;
#Override
public void onParentListItemExpanded(int position) {
List<? extends ParentListItem> parentItemList = this.getParentItemList();
collapseAllParents();
int finalPos = position;
if (lastPos != -1 && lastPos < position) {
finalPos = position - parentItemList.get(lastPos).getChildItemList().size();
}
expandParent(finalPos);
mRecyclerView.smoothScrollToPosition(finalPos);
lastPos = position;
}
I found this issue at https://github.com/bignerdranch/expandable-recycler-view/issues/156 . Although the solution given there didn't work. Slight tweaking to that make it work.
Use this following code in your expandable listview click listener. Do something liket his
yourExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean onGroupClick(final ExpandableListView parent, View v, final int groupPosition, long id) {
....
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
parent.smoothScrollToPositionFromTop(groupPosition + 1, 0);
}
},100);
....
return true;
}
});
Use AnimatedExpandableListView
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 :)
I'm using RecyclerView, I have one ImageButton as Child view, I'm changing the background of that ImageButton on click.
Now my problem is when change Image of ImageButton by clicking and than scroll up again scroll to the top, the state of set to the initial stage. I tried everything but its not happening. help me with that.
My Adapter class
public class ViewAllAdapter extends RecyclerView.Adapter<ProductHolder> {
int[] objects;
Context context;
Boolean flag = false;
public ViewAllAdapter(int[] objects, Context context) {
super();
this.objects = objects;
this.context = context;
}
#Override
public int getItemCount() {
return objects.length;
}
#Override
public void onBindViewHolder(final ProductHolder arg0, int arg1) {
arg0.title.setText("Product" + arg1 + 1);
arg0.aPrice.setPaintFlags(arg0.aPrice.getPaintFlags()
| Paint.STRIKE_THRU_TEXT_FLAG);
arg0.aPrice.setText("\u20B9" + " " + "5000");
arg0.off.setText("56% off");
arg0.price.setText("\u20B9" + " " + "2300");
arg0.mainImage.setImageResource(objects[arg1]);
arg0.ratings.setRating(4f);
arg0.clickme.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,
ProductDetailsPage.class);
startActivity(i);
}
});
arg0.wish.setBackgroundResource(R.drawable.heart);
arg0.wish.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!flag) {
arg0.wish.setBackgroundResource(R.drawable.heartfade);
YoYo.with(Techniques.Tada).duration(550)
.playOn(arg0.wish);
Toast.makeText(context, "Product Added to wish list..",
Toast.LENGTH_SHORT).show();
flag = true;
} else {
arg0.wish.setBackgroundResource(R.drawable.heart);
Toast.makeText(context,
"Product Removed to wish list..",
Toast.LENGTH_SHORT).show();
flag = false;
}
}
});
}
#Override
public ProductHolder onCreateViewHolder(ViewGroup arg0, int arg1) {
LayoutInflater inflater = LayoutInflater.from(arg0.getContext());
View view = inflater.inflate(R.layout.viewall_item, arg0, false);
return new ProductHolder(view);
}
public class ProductHolder extends RecyclerView.ViewHolder {
protected TextView title;
protected TextView aPrice;
protected TextView off;
protected TextView price;
protected ImageView mainImage;
protected RatingBar ratings;
protected ImageButton wish;
protected RelativeLayout clickme;
public ProductHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.productName);
aPrice = (TextView) itemView
.findViewById(R.id.productActualPrice);
off = (TextView) itemView.findViewById(R.id.offPrice);
price = (TextView) itemView.findViewById(R.id.productPrice);
mainImage = (ImageView) itemView
.findViewById(R.id.productImage);
wish = (ImageButton) itemView.findViewById(R.id.addToWishList);
ratings = (RatingBar) itemView
.findViewById(R.id.productRatings);
clickme = (RelativeLayout) itemView
.findViewById(R.id.clickToGO);
}
}
}
And in My MainActicity I'm doing
rv = (RecyclerView) findViewById(R.id.gvViewAll);
rv.setHasFixedSize(true);
GridLayoutManager glm = new GridLayoutManager(getApplicationContext(),
2);
rv.setLayoutManager(glm);
final ViewAllAdapter adp = new ViewAllAdapter(productImage,
getApplicationContext());
rv.setAdapter(adp);
rvh = (RecyclerViewHeader) findViewById(R.id.header);
rvh.attachTo(rv, true);
Thanks for any help.
As per your Custom RecyclerView adapter, I suggest you to use HashMap to store Values. After all Data Model is best option to load data in to RecyclerView.
HashMap<Integer, Integer> hashMapTest = new HashMap<>();
When user click on ImageButton then add following code:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(hashMapTest.get(position) != null && hashMapTest.get(position) != false) {
// Code of Product Added to wish list..
hashMapTest.put(getPosition(), 1);
} else {
// Code of Product Removed to wish list..
hashMapTest.put(getPosition(), 0);
}
}
});
In your onBindViewHolder(ProductHolder holder, int position) add following code
if(hashMapTest.get(position) != null && hashMapTest.get(position) != false) {
// Show your ImageButton color Product Added to wish list..
} else {
// Show your ImageButton color Product Removed to wish list..
}
Hope it helps you.