我想更新我的按钮ListView
。我目前拥有的代码工作正常,但有一个小故障,当到达最后一项时,它会突然用上一篇文章中的错误数据更新第一项,因为它是最后一篇文章。我不知道会发生什么,在我的日志我没有得到任何表明第一项正在更新的信息。我从这个类似的问题中得到了这个代码和想法。
这是我使用的代码:
/**
* 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);
}
}
每次用户滚动列表视图时,我都会运行此代码:
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();
}
});