I want to update my buttons in a ListView
. The code I currently have works fine but has a glitch, when reaching to the last item it suddenly updates the first item too with the wrong data from the last post as it is the last post.I don't know what happens, in my log I get nothing that indicates the first item is being updated.
I got this code and idea from this similar question.
Here is the code I use:
/**
* Updates the like/dislike button states
*/
public void updateButtons() {
ListView lv = ((ListView) findViewById(R.id.post_list));
Log.d("Child Count: ", Integer.toString(lv.getCount()));
int firstVisible;
int child;
for(int i=0; i < lv.getCount(); i++) {
firstVisible = lv.getFirstVisiblePosition() - lv.getHeaderViewsCount();
child = i - firstVisible;
if(child < 0 || child >= lv.getChildCount()) {
continue;
}
if(updated.contains(i)) continue;
Log.d("Debug", "Updating child:" + Integer.toString(child));
LinearLayout row = (LinearLayout) lv.getChildAt(child);
if(likeable.get(i) == 0) {
LinearLayout btn = (LinearLayout) row.findViewById(R.id.btn_like);
btn.setClickable(false);
ImageView imgView = (ImageView) row.findViewById(R.id.img_like);
imgView.setImageDrawable(getResources().getDrawable(R.drawable.ic_like_selected));
TextView txtView = (TextView) row.findViewById(R.id.text_like);
txtView.setTextColor(Color.parseColor("#60007c"));
}
if(dislikeable.get(i) == 0) {
LinearLayout btn = (LinearLayout) row.findViewById(R.id.btn_dislike);
btn.setClickable(false);
ImageView imgView = (ImageView) row.findViewById(R.id.img_dislike);
imgView.setImageDrawable(getResources().getDrawable(R.drawable.ic_dislike_selected));
TextView txtView = (TextView) row.findViewById(R.id.text_dislike);
txtView.setTextColor(Color.parseColor("#60007c"));
}
Log.d("Debug", "Adding child" + Integer.toString(i) + "TO the updated list");
updated.add(i);
}
}
I run this code everytime the user scrolls the listview :
ListView lv = ((ListView) findViewById(R.id.post_list));
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
updateButtons();
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
updateButtons();
}
});