hide section labels in listview - android

I use component android-section-list (http://code.google.com/p/android-section-list/) to create sections in my listView. How can I hide sections after push some button?
I try to do like
public void onClick(View v) {
switch(v.getId()) {
case R.id.sortTitle:
LayoutInflater inflater = (LayoutInflater) this.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View convertView = inflater.inflate(R.layout.market_list_separator, null, false);
TextView separatorLayout = (TextView) convertView.findViewById(R.id.section_view);
separatorLayout.setVisibility(View.GONE);
sectionAdapter.notifyDataSetChanged();
setButtonState(sortByTitle);
adapter.sort((Comparator<SectionListItem>) sortByTitle());
break;
}
}
But this way don't work.
My adapter put data in list rows and SectionListAdapter draw sections.
public class SectionListAdapter extends BaseAdapter implements ListAdapter,
OnItemClickListener {
private final DataSetObserver dataSetObserver = new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
updateSessionCache();
}
#Override
public void onInvalidated() {
super.onInvalidated();
updateSessionCache();
};
};
private final ListAdapter linkedAdapter;
private final Map<Integer, String> sectionPositions = new LinkedHashMap<Integer, String>();
private final Map<Integer, Integer> itemPositions = new LinkedHashMap<Integer, Integer>();
private final Map<View, String> currentViewSections = new HashMap<View, String>();
private int viewTypeCount;
protected final LayoutInflater inflater;
private View transparentSectionView;
private OnItemClickListener linkedListener;
public SectionListAdapter(final LayoutInflater inflater,
final ListAdapter linkedAdapter) {
this.linkedAdapter = linkedAdapter;
this.inflater = inflater;
linkedAdapter.registerDataSetObserver(dataSetObserver);
updateSessionCache();
}
private boolean isTheSame(final String previousSection,
final String newSection) {
if (previousSection == null) {
return newSection == null;
} else {
return previousSection.equals(newSection);
}
}
private synchronized void updateSessionCache() {
int currentPosition = 0;
sectionPositions.clear();
itemPositions.clear();
viewTypeCount = linkedAdapter.getViewTypeCount() + 1;
String currentSection = null;
final int count = linkedAdapter.getCount();
for (int i = 0; i < count; i++) {
final SectionListItem item = (SectionListItem) linkedAdapter
.getItem(i);
if (!isTheSame(currentSection, item.section)) {
sectionPositions.put(currentPosition, item.section);
currentSection = item.section;
currentPosition++;
}
itemPositions.put(currentPosition, i);
currentPosition++;
}
}
public synchronized int getCount() {
return sectionPositions.size() + itemPositions.size();
}
public synchronized Object getItem(final int position) {
if (isSection(position)) {
return sectionPositions.get(position);
} else {
final int linkedItemPosition = getLinkedPosition(position);
return linkedAdapter.getItem(linkedItemPosition);
}
}
public synchronized boolean isSection(final int position) {
return sectionPositions.containsKey(position);
}
public synchronized String getSectionName(final int position) {
if (isSection(position)) {
return sectionPositions.get(position);
} else {
return null;
}
}
public long getItemId(final int position) {
if (isSection(position)) {
return sectionPositions.get(position).hashCode();
} else {
return linkedAdapter.getItemId(getLinkedPosition(position));
}
}
protected Integer getLinkedPosition(final int position) {
return itemPositions.get(position);
}
#Override
public int getItemViewType(final int position) {
if (isSection(position)) {
return viewTypeCount - 1;
}
return linkedAdapter.getItemViewType(getLinkedPosition(position));
}
private View getSectionView(final View convertView, final String section) {
View theView = convertView;
if (theView == null) {
theView = createNewSectionView();
}
setSectionText(section, theView);
replaceSectionViewsInMaps(section, theView);
return theView;
}
protected void setSectionText(final String section, final View sectionView) {
final TextView textView = (TextView) sectionView.findViewById(R.id.listTextView);
textView.setText(section);
}
protected synchronized void replaceSectionViewsInMaps(final String section,
final View theView) {
if (currentViewSections.containsKey(theView)) {
currentViewSections.remove(theView);
}
currentViewSections.put(theView, section);
}
protected View createNewSectionView() {
return inflater.inflate(R.layout.section_view, null);
}
public View getView(final int position, final View convertView,
final ViewGroup parent) {
if (isSection(position)) {
return getSectionView(convertView, sectionPositions.get(position));
}
return linkedAdapter.getView(getLinkedPosition(position), convertView,
parent);
}
#Override
public int getViewTypeCount() {
return viewTypeCount;
}
#Override
public boolean hasStableIds() {
return linkedAdapter.hasStableIds();
}
#Override
public boolean isEmpty() {
return linkedAdapter.isEmpty();
}
#Override
public void registerDataSetObserver(final DataSetObserver observer) {
linkedAdapter.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(final DataSetObserver observer) {
linkedAdapter.unregisterDataSetObserver(observer);
}
#Override
public boolean areAllItemsEnabled() {
return linkedAdapter.areAllItemsEnabled();
}
#Override
public boolean isEnabled(final int position) {
if (isSection(position)) {
return true;
}
return linkedAdapter.isEnabled(getLinkedPosition(position));
}
public void makeSectionInvisibleIfFirstInList(final int firstVisibleItem) {
final String section = getSectionName(firstVisibleItem);
// only make invisible the first section with that name in case there
// are more with the same name
boolean alreadySetFirstSectionIvisible = false;
for (final Entry<View, String> itemView : currentViewSections
.entrySet()) {
if (itemView.getValue().equals(section)
&& !alreadySetFirstSectionIvisible) {
itemView.getKey().setVisibility(View.INVISIBLE);
alreadySetFirstSectionIvisible = true;
} else {
itemView.getKey().setVisibility(View.VISIBLE);
}
}
for (final Entry<Integer, String> entry : sectionPositions.entrySet()) {
if (entry.getKey() > firstVisibleItem + 1) {
break;
}
setSectionText(entry.getValue(), getTransparentSectionView());
}
}
public synchronized View getTransparentSectionView() {
if (transparentSectionView == null) {
transparentSectionView = createNewSectionView();
}
return transparentSectionView;
}
protected void sectionClicked(final String section) {
//
}
public void onItemClick(final AdapterView< ? > parent, final View view,
final int position, final long id) {
if (isSection(position)) {
sectionClicked(getSectionName(position));
} else if (linkedListener != null) {
linkedListener.onItemClick(parent, view,
getLinkedPosition(position), id);
}
}
public void setOnItemClickListener(final OnItemClickListener linkedListener) {
this.linkedListener = linkedListener;
}
}
Where can I put check for visibility in this Adapter?

This works but will be overwritten by the getView() method in the adapter . You must handle this in the adapter bcoz each time view becomes visible on the screen the View is updated so becomes visible in your case.
For the Data you are storing add a Visibility field ( by default keep it visible ) and change the Visibility to GONE in the onClick() method.
if you dont understand , post me your code and will let you know what changes to make.

Related

Android ListView glitching back to top for a few seconds before it works properly

I am trying to make an application with a ListView that include a Country Flag and name. This is so that the user can click on them and be shown images of the country that they wouldve taken before. However for about 3 seconds when the listview loads if i try to scroll it will sort of glitch and send me back to top. This is the code..
public class CountriesListAdapter extends ArrayAdapter {
private int resource;
private LayoutInflater inflater;
private List<CountryModel> countryModels;
private WeakReference<TextView> selectedCountryIdtxt;
private boolean useFilter;
private WeakReference<ProgressBar> progressBarWeakReference;
public int getSelectedCountryId() {
return selectedCountryId;
}
public void setSelectedCountryId(int selectedCountryId) {
this.selectedCountryId = selectedCountryId;
}
private int selectedCountryId;
public CountriesListAdapter(#NonNull WeakReference<Context> context, int resourceId, WeakReference<TextView> textView, #NonNull List<CountryModel> countryModelList, boolean useFilter, WeakReference<ProgressBar> progressBarWeakReference){
super(context.get(), resourceId, countryModelList);
selectedCountryIdtxt = textView;
resource = resourceId; //the id of the template file
inflater = LayoutInflater.from(context.get());
this.countryModels = countryModelList;
selectedCountryId = -1;
this.useFilter = useFilter;
this.progressBarWeakReference = progressBarWeakReference;
}
public int getCount() {
if (countryModels != null)
return countryModels.size();
return 0;
}
public CountryModel getItem(int position) {
if (countryModels != null)
return countryModels.get(position);
return null;
}
public long getItemId(int position) {
if (countryModels != null)
return countryModels.get(position).hashCode();
return 0;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
// this method is automatically called for every object in our list
//basically it's called for every single row before it is generated
// this method is called per row
convertView = (ConstraintLayout) inflater.inflate(resource, null);
//the variable countryModel is fiiled with current object that is being processed
final CountryModel countryModel = countryModels.get(position);
TextView countryName = convertView.findViewById(R.id.countryNamelbl);
final ImageView countryFlag = convertView.findViewById(R.id.countryFlagimg);
final ImageView checked = convertView.findViewById(R.id.countryCheckedimg);
//this is done for every object in the list
assert countryModel != null;
countryName.setText(countryModel.getName());
Picasso.get().load(countryModel.getImage()).fit().into(countryFlag);
if(!useFilter) {
if (selectedCountryId == countryModel.getId()) {
checked.setVisibility(View.VISIBLE);
} else {
checked.setVisibility(View.INVISIBLE);
}
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!useFilter) {
if (checked.getVisibility() == View.VISIBLE) {
checked.setVisibility(View.INVISIBLE);
selectedCountryId = -1;
selectedCountryIdtxt.get().setText(String.valueOf(selectedCountryId));
} else {
if (selectedCountryId == -1) {
checked.setVisibility(View.VISIBLE);
selectedCountryId = countryModel.getId();
} else {
selectedCountryId = countryModel.getId();
notifyDataSetChanged();
}
selectedCountryIdtxt.get().setText(String.valueOf(selectedCountryId));
}
} else {
Intent i = new Intent(getContext(), PicturesActivity.class);
i.putExtra("countryId",countryModel.getId());
i.putExtra("countryName", countryModel.getName());
getContext().startActivity(i);
}
}
});
progressBarWeakReference.get().setVisibility(View.INVISIBLE);
return convertView;
}
public List<CountryModel> getCountryModels() {
return countryModels;
}
public void setCountryModels(List<CountryModel> countryModels) {
this.countryModels = countryModels;
}
}
The problem was actually in another class, i was calling the adapter for every list item instead of just once... oops.
Thanks for the replies though!

How to disable previous items in a ListView

I am trying to develop an activity where there is a custom listView made out of CustomAdapter.
The list consists of a TextView and an EditText. The EditText when clicked, it auto fetches the system time.
What I want is when a particular EditText is filled, I want all the previous(above) list items in the sequence to be disabled.
So far, I have tried using isEnabled() and areAllItemsEnabled() functions returning respective boolean values using position, but however didn’t work.
Please help me achieve the above.
Thanks.
This is my CustomAdapter Class
public class SelectStnListByRoute extends BaseAdapter implements View.OnClickListener {
Context context;
ArrayList<StnNames> stnList;
LayoutInflater layoutInflater = null;
ViewHolder viewHolder;
private int mLastClicked;
public SelectStnListByRoute(Context context, ArrayList<StnNames> stnList) {
super();
this.context = context;
this.stnList = stnList;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return stnList.size();
}
#Override
public Object getItem(int position) {
return stnList.get(position);
}
#Override
public long getItemId(int position) {
return stnList.indexOf(getItem(position));
}
public int getViewTypeCount() {
return 1;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
if(position==position){
return false;
}
return false;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
int type = getItemViewType(position);
StnNames stnDetails = stnList.get(position);
viewHolder = new ViewHolder();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.footplate_custome_layout, null);
viewHolder.txtStnNAme = (TextView) convertView.findViewById(R.id.txtStnCode);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
viewHolder.txtStnDep = (TextView) convertView.findViewById(R.id.txtDepTime);
convertView.setTag(viewHolder);
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
} else {
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
}
viewHolder.txtStnNAme.setText(stnDetails.getStnCode());
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: " , String.valueOf(position)); //Here I am getting the position of the row item clicked, where should I put the Onclick false for disabling all of the above fields using the position?
}
});
viewHolder.txtStnDep.setOnClickListener(this);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
if (stnDetails.getArrivalTime() != null) {
viewHolder.txtStnArr.setText(stnDetails.getArrivalTime());
} else {
viewHolder.txtStnArr.setText("");
}
if (stnDetails.getDeptTime() != null) {
viewHolder.txtStnDep.setText(stnDetails.getDeptTime());
} else {
viewHolder.txtStnDep.setText("");
}
return convertView;
}
class ViewHolder {
TextView txtStnNAme, txtStnArr, txtStnDep;
int ref;
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case txtArrivalTime:
TextView textViewArrVal = (TextView) view.findViewById(R.id.txtArrivalTime);
textViewArrVal.setClickable(false);
StnNames listItemsArrr = (StnNames) textViewArrVal.getTag();
if (listItemsArrr.getArrivalTime() != getCurrentTime()) {
listItemsArrr.setArrivalTime(getCurrentTime());
if (listItemsArrr.getArrivalTime() != null) {
int position = textViewArrVal.getSelectionStart();
textViewArrVal.setText(listItemsArrr.getArrivalTime());
} else {
textViewArrVal.setText("");
}
}
break;
case txtDepTime:
TextView textViewDepVal = (TextView) view.findViewById(R.id.txtDepTime);
StnNames listItemsDepp = (StnNames) textViewDepVal.getTag();
if (listItemsDepp.getDeptTime() != getCurrentTime()) {
listItemsDepp.setDeptTime(getCurrentTime());
if (listItemsDepp.getDeptTime() != null) {
textViewDepVal.setText(listItemsDepp.getDeptTime());
} else {
textViewDepVal.setText("");
}
}
break;
default:
break;
}
}
public String getCurrentTime(){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String arrDate = mdformat.format(calendar.getTime());
return arrDate;
}
}
You can do this as below mentioned -:
You need to store the position of clicked button was. So initialize a variable in your class
int mButtonSelected = -1;
EDIT 1.
Then make a change to your isEnabled method
#Override
public boolean isEnabled(int position) {
if(position<mButtonSelected){
return false;
}
return true;
}
That will work it if any other button was clicked. but you have to do that in your onClick
mButtonSelected = position;
notifyDataSetChanged();
Let me it worked or not
EDIT
see below changes in your code-:
public class SelectStnListByRoute extends BaseAdapter {
Context context;
ArrayList<StnNames> stnList;
LayoutInflater layoutInflater = null;
ViewHolder viewHolder;
private int mLastClicked;
private SQLiteDB sqLiteDB;
int mArrivalSelected = -1;
int mDepartSelected = -1;
public SelectStnListByRoute(Context context, ArrayList<StnNames> stnList) {
super();
this.context = context;
this.stnList = stnList;
layoutInflater = LayoutInflater.from(context);
sqLiteDB = new SQLiteDB(context);
}
#Override
public int getCount() {
return stnList.size();
}
#Override
public Object getItem(int position) {
return stnList.get(position);
}
#Override
public long getItemId(int position) {
return stnList.indexOf(getItem(position));
}
public int getViewTypeCount() {
return 1;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
if (position <= mArrivalSelected) {
return false;
}
return true;
}
public boolean isEnabledd(int position) {
if (position <= mDepartSelected) {
return false;
}
return true;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
int type = getItemViewType(position);
StnNames stnDetails = stnList.get(position);
viewHolder = new ViewHolder();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.footplate_custome_layout, null);
viewHolder.txtStnNAme = (TextView) convertView.findViewById(R.id.txtStnCode);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
viewHolder.txtStnDep = (TextView) convertView.findViewById(R.id.txtDepTime);
convertView.setTag(viewHolder);
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
} else {
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
}
viewHolder.txtStnNAme.setText(stnDetails.getStnCode());
if (!isEnabled(position)) {
if (position <= mArrivalSelected) {
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnArr.setEnabled(false);
if (position < mArrivalSelected) {
viewHolder.txtStnDep.setEnabled(false);
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#ffa500"));
}
}
} else {
viewHolder.txtStnArr.setEnabled(true);
viewHolder.txtStnDep.setEnabled(true);
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#b4b4b4"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#b4b4b4"));
}
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: ", String.valueOf(position));
mArrivalSelected = position;
arrivalClick(view);
notifyDataSetChanged();
}
});
if (!isEnabledd(position)) {
if (position <= mDepartSelected) {
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnArr.setEnabled(false);
viewHolder.txtStnDep.setEnabled(false);
} else {
viewHolder.txtStnArr.setEnabled(true);
viewHolder.txtStnDep.setEnabled(true);
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#b4b4b4"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#b4b4b4"));
}
}
viewHolder.txtStnDep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: ", String.valueOf(position));
mDepartSelected = position;
departureClick(view);
notifyDataSetChanged();
}
});
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
if (stnDetails.getArrivalTime() != null) {
viewHolder.txtStnArr.setText(stnDetails.getArrivalTime());
} else {
viewHolder.txtStnArr.setText("");
}
if (stnDetails.getDeptTime() != null) {
viewHolder.txtStnDep.setText(stnDetails.getDeptTime());
} else {
viewHolder.txtStnDep.setText("");
}
return convertView;
}
class ViewHolder {
TextView txtStnNAme, txtStnArr, txtStnDep;
StnNames pos;
int ref;
}
public void arrivalClick(View view) {
TextView textViewArrVal = (TextView) view.findViewById(R.id.txtArrivalTime);
StnNames listItemsArrr = (StnNames) textViewArrVal.getTag();
if (listItemsArrr.getArrivalTime() != getCurrentTime()) {
listItemsArrr.setArrivalTime(getCurrentTime());
int stnId = listItemsArrr.getStnId();
String arrClick = "arrival";
String upSideKm = listItemsArrr.getStnUpsideKm();
String downsideKm = listItemsArrr.getStnDownSideKm();
String arrTime = getCurrentTime();
/* sqLiteDB.open();
*//* long abc = sqLiteDB.insertJourneySchedule(stnId,arrTime,"",userId,journeyId,latitute,longitute,journyDate,arrClick);*//*
*//* long abcd = sqLiteDB.updateJourneySchedule(stnId,arrTime,"",userId,journeyId,latitute,longitute,journyDate,arrClick,downsideKm,upSideKm);
Log.e("arrclick",String.valueOf(abcd));*//*
sqLiteDB.close();*/
if (listItemsArrr.getArrivalTime() != null) {
int position = textViewArrVal.getSelectionStart();
textViewArrVal.setText(listItemsArrr.getArrivalTime());
} else {
textViewArrVal.setText("");
}
}
}
public void departureClick(View view) {
TextView textViewDepVal = (TextView) view.findViewById(R.id.txtDepTime);
StnNames listItemsDepp = (StnNames) textViewDepVal.getTag();
if (listItemsDepp.getDeptTime() != getCurrentTime()) {
listItemsDepp.setDeptTime(getCurrentTime());
String depTime = getCurrentTime();
int stnId = listItemsDepp.getStnId();
String depClick = "departure";
String upSideKm = listItemsDepp.getStnUpsideKm();
String downsideKm = listItemsDepp.getStnDownSideKm();
sqLiteDB.open();
/*long abc = sqLiteDB.insertJourneySchedule(stnId,"",depTime,userId,journeyId,latitute,longitute,journyDate,depClick);*/
/*long abcd = sqLiteDB.updateJourneySchedule(stnId,"",depTime,userId,journeyId,latitute,longitute,journyDate,depClick,downsideKm,upSideKm);
Log.e("depclick",String.valueOf(abcd));*/
sqLiteDB.close();
if (listItemsDepp.getDeptTime() != null) {
textViewDepVal.setText(listItemsDepp.getDeptTime());
} else {
textViewDepVal.setText("");
}
}
}
public String getCurrentTime() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String arrDate = mdformat.format(calendar.getTime());
return arrDate;
}
}
Get the position of the row which is clicked and then set onclick false for positions less than clicked position
as follows:
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: " , String.valueOf(position));
for (int i = 0; i < position; i++) {
viewHolder.txtStnArr.setEnable(false);
}
notifyDataSetChanged();
}
});

notifyItemChanged method does not call onBindViewHolder in recyclerview

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

ListView repeating the data on load more

I am using on scroll to load more data and show them in list view but my ListView first shows already loaded data then adds the newly added data to ListView
I have used for reference this and many others but unable to solve the issue
Here is my activity class
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all);
ButterKnife.bind(this);
Users = Users.getCurrentUser(this);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
UIUtility.setStatusColor(this);
Intent intent = getIntent();
try {
entityData = new JSONArray(intent.getStringExtra(EXTRA_DATA));
} catch (JSONException e) {
e.printStackTrace();
}
viewAllCategory = intent.getIntExtra(EXTRA_CATEGORY, 0);
viewAllEntityType = intent.getIntExtra(EXTRA_TYPE, 0);
latitude = intent.getDoubleExtra(EXTRA_LATITUDE, 0);
longitude = intent.getDoubleExtra(EXTRA_LONGITUDE, 0);
setTitle(TITLES[viewAllCategory]);
if (viewAllEntityType == Constants.SMBEntityType.TYPE_USER) {
List<Users> users = Utility.convertJsonArrayToUsers(entityData);
adapterUser = new ViewAllUserAdapter(this, users);
lvEntity.setAdapter(adapterUser);
} else {
List<Book> books = Utility.convertJsonArrayToBook(entityData);
adapterBook = new ViewAllBookAdapter(this, books);
lvEntity.setAdapter(adapterBook);
}
lvEntity.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (!stopLoadingMore) {
if (totalItemCount == firstVisibleItem + visibleItemCount && !isLoading) {
isLoading = true;
showLoading();
loadMoreData();
}
}
}
});
}
private void loadMoreData() {
String loadMoreUrl = buildLoadMoreUrl();
ShareMyBookHttpClient client = new ShareMyBookHttpClient();
client.get(loadMoreUrl, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
hideLoading();
if (responseBody != null) {
start = start+20;
try {
JSONObject jo = new JSONObject(new String(responseBody));
if (!jo.getBoolean(Constants.JsonKeys.ERROR)) {
JSONArray data = jo.getJSONArray(Constants.JsonKeys.DATA);
if (data.length() == 0) {
stopLoadingMore = true;
return;
}
if (data.length() < 20) {
stopLoadingMore = true;
}
for (int i = 0; i < data.length(); i++) {
entityData.put(data.getJSONObject(i));
}
if (viewAllEntityType == Constants.SMBEntityType.TYPE_USER) {
List<Users> users = Utility.convertJsonArrayToUsers(entityData);
adapterUser.mergeArray(users);
} else {
List<Book> books = Utility.convertJsonArrayToBook(entityData);
adapterBook.mergeArray(books);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
hideLoading();
}
});
}
private String buildLoadMoreUrl() {
switch (viewAllCategory) {
default:
case ViewAllCategory.CATEGORY_USER:
return Constants.createUrlToGetViewAllUsers(Users.getId(), latitude, longitude, Users.getAuthToken(), start, LIMIT);
case ViewAllCategory.CATEGORY_MY_BOOKS:
return Constants.createUrlToGetViewAllMyBooks(Users.getId(), Users.getAuthToken(), start, LIMIT);
}
}
private void showLoading() {
sbLoading = Snackbar.make(coolMain, R.string.view_all_loading, Snackbar.LENGTH_INDEFINITE);
sbLoading.show();
}
private void hideLoading() {
isLoading = false;
if (sbLoading != null) {
sbLoading.dismiss();
}
}
and following is my AdapterClasss
public class ViewAllUserAdapter extends BaseAdapter {
private List<Users> users;
private Context context;
public ViewAllUserAdapter(Context context, List<Users> usersData) {
this.context = context;
users = usersData;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
UserVH holder=null;
if(row==null) {
LayoutInflater inflater = LayoutInflater.from(context);
row= inflater.inflate(R.layout.list_item_view_all_user, parent, false);
holder = new UserVH(row, position);
Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
row.setTag(holder);
}
else {
holder=(UserVH)row.getTag();Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
}
return row;
}
#Override
public int getCount() {
return users == null ? 0 : users.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public void mergeArray(List<Users> additionalUsers) {
Log.e("users", String.valueOf(additionalUsers.size()));
if (additionalUsers != null) {
for (int i = 0; i < additionalUsers.size(); i++) {
if(!(users.contains(additionalUsers.get(i)))) {
users.add(additionalUsers.get(i));
}
}
}
notifyDataSetChanged();
}
public class UserVH extends View {
#Bind(R.id.item_vau_iv_user_image)
ImageView ivUserImage;
#Bind(R.id.item_vau_tv_name)
TextView tvName;
#Bind(R.id.item_vau_tv_distance)
TextView tvDistance;
private int position;
public UserVH(View view, final int position) {
super(context);
this.position = position;
ButterKnife.bind(this, view);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
UIUtility.openUserDetailActivity(context, users.get(position));
}
});
}
}
}
As you already referred this link, Exactly the same issue is happening with you, You should have correct implementation for holder class in getView method.
Update your getView() method as per below :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
UserVH holder=null;
if(row==null) {
LayoutInflater inflater = LayoutInflater.from(context);
row= inflater.inflate(R.layout.list_item_view_all_user, parent, false);
holder = new UserVH(row, position);
row.setTag(holder);
}
else {
holder=(UserVH)row.getTag();
}
Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
return row;
}
And update your getItemId and getItem methods as per below :
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
EDIT : clear the list additional users before adding the new objects
public void mergeArray(List<Users> additionalUsers) {
Log.e("users", String.valueOf(additionalUsers.size()));
if (additionalUsers != null) {
// Following line to be added
additonalusers.clear();
for (int i = 0; i < additionalUsers.size(); i++) {
if(!(users.contains(additionalUsers.get(i)))) {
users.add(additionalUsers.get(i));
}
}
}
notifyDataSetChanged();
}
Your implementation of following methods is incorrect.
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
Change them as below
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}

ListView items repetition

Now I have a list view with a custom adapter which shows a different layout types.
List view items are repeating in a random manner and I can't figure out the problem.
So, can anybody help please?
Here is my code.
public class NewsFeedAdapter extends BaseAdapter {
private final int IMAGE_COMPARISON = 0;
private final int POLL = 1;
private final int EMO = 2;
private final int TYPE_MAX_COUNT = EMO + 1;
private ArrayList<Post> posts = new ArrayList<Post>();
private ArrayList<Post> originalPosts = new ArrayList<Post>();
private MaterialDialog alert;
private Context context;
private ApiClient apiClient;
private SharedPreferences sharedPreferences;
private int id;
private Bitmap bitmap;
private ArrayList<View> views ;
private Intent sharingIntent;
private String link;
private String type;
public NewsFeedAdapter(Context context, ArrayList<Post> questionItems) {
this.context = context;
this.posts = questionItems;
this.originalPosts = new ArrayList<Post>(posts);
this.apiClient = ApiClient.getInstance(context);
sharedPreferences = context.getSharedPreferences(context.getResources().getStringArray(R.array.preferences)[4], 0);
views = new ArrayList<>();
}
#Override
public int getCount() {
return posts.size();
}
#Override
public Object getItem(int position) {
return posts.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getItemViewType(int position) {
String type = ((Post)getItem(position)).getQ().getType();
if(type.equalsIgnoreCase("radio")){
return POLL;
}else if(type.equalsIgnoreCase("image")){
return IMAGE_COMPARISON;
}else{
return EMO;
}
}
public int getItemViewType(Post post) {
String type = (post).getQ().getType();
if(type.equalsIgnoreCase("radio")){
return POLL;
}else if(type.equalsIgnoreCase("image")){
return IMAGE_COMPARISON;
}else{
return EMO;
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
switch (type) {
case IMAGE_COMPARISON:
ImageListRowView imageListRowView;
// if (convertView == null) {
imageListRowView = new ImageListRowView(context, new MenuListener() {
#Override
public void onReceive(MenuItemAction menuItemAction,int position) {
preformMenuAction(menuItemAction, position);
}
});
imageListRowView.setData(posts.get(position));
imageListRowView.setTag(R.string.view_tag,position);
views.add(imageListRowView);
return imageListRowView;
// }
// else
// imageListRowView = (ImageListRowView) convertView;
//return imageListRowView;
{
case EMO:
EmoListRowView emoListRowView;
// if (convertView == null) {
emoListRowView = new EmoListRowView(context, new MenuListener() {
#Override
public void onReceive(MenuItemAction menuItemAction,int position) {
preformMenuAction(menuItemAction, position);
}
});
emoListRowView.setData(posts.get(position));
emoListRowView.setTag(R.string.view_tag,position);
views.add(emoListRowView);
return emoListRowView;
// }
// else
// emoListRowView = (EmoListRowView) convertView;
// return emoListRowView;
case POLL:
PollListRowView pollListRowView;
// if (convertView == null) {
pollListRowView = new PollListRowView(context, new MenuListener() {
#Override
public void onReceive(MenuItemAction menuItemAction,int position) {
preformMenuAction(menuItemAction, position);
}
});
pollListRowView.setData(posts.get(position));
pollListRowView.setTag(R.string.view_tag,position);
views.add(pollListRowView);
return pollListRowView;
}
// else
// pollListRowView = (PollListRowView) convertView;
// return pollListRowView;
}
return convertView;
}
getView() needs to always customize the rows. The only variance based upon whether convertView is null is whether you have to also inflate the rows.
In each of your case blocks, if convertView is not null, you just return convertView without modification.
give a look at the following question.I think your problem resembles this one.
After scrolling listview, listview items getting repeatedly in android

Categories

Resources