我使用实现 ViewHolder 模式的基本适配器创建了一个 listView。listview 中的每个项目都有一个倒计时计时器。工作正常,但如果我想更新 listview countDownTimer 在新值和旧值之间闪烁。
如何解决这个问题?
基适配器 getView()
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
rowView = inflater.inflate(R.layout.row_item, null);
ViewHolder viewHolder = new ViewHolder();
rowView.setTag(viewHolder);
viewHolder.name = (TextView) rowView.findViewById(R.id.name);
viewHolder.startingAt = (TextView) rowView.findViewById(R.id.starting_at);
} else {
rowView = convertView;
}
ViewHolder holder = (ViewHolder) rowView.getTag();
Model current = list.get(position);
holder.name.setText(current.name);
return rowView;
}
每个项目的 CountDownTimer
@Override
public void run() {
int j = 0;
for (int nTime : listOfTimes) {
listOfTimes.set(j, nTime - 1);
j++;
}
if (lv.getCount() <= 0) {
return;
}
int nAmountVisible = lv.getLastVisiblePosition() - lv.getFirstVisiblePosition();
for (int i = 0; i <= nAmountVisible; i++) {
long lTimeFromList = listOfTimes.get(lv.getFirstVisiblePosition() + i);
// transform timestamp to readable date
long weeks = TimeUnit.SECONDS.toDays(lTimeFromList) / 7;
long days = TimeUnit.SECONDS.toDays(lTimeFromList) - (7 * weeks);
long hours = TimeUnit.SECONDS.toHours(lTimeFromList) - TimeUnit.DAYS.toHours(days) - TimeUnit.DAYS.toHours(7 * weeks);
long minute = TimeUnit.SECONDS.toMinutes(lTimeFromList) - (TimeUnit.SECONDS.toHours(lTimeFromList) * 60);
long second = TimeUnit.SECONDS.toSeconds(lTimeFromList) - (TimeUnit.SECONDS.toMinutes(lTimeFromList) * 60);
View viewHolder = lv.getChildAt(i);
AuctionAdapter.ViewHolder localHolder = (AuctionAdapter.ViewHolder) viewHolder.getTag();
viewHolder.invalidate();
localHolder.startingAt.setText(weeks + "w " + days + "d " + hours + "h " + minute + "m " + second + "s ");
}
mHandler.postDelayed(this, 1000);
}
和来自填充适配器的片段的代码和倒数计时器的时间列表
baseAdapter = new baseAdapter(getActivity(),list);
baseAdapter.notifyDataSetChanged();
runningLv.setAdapter(baseAdapter);
runningLv.invalidateViews();
ArrayList<Integer> listOfTimes = new ArrayList<Integer>();
listOfTimes.clear();
for (Model m : list) {
listOfTimes.add(Integer.parseInt(m.starting_at) - m.current_time);
}
CountDownTime countDownTimer = new CountDownTime(listOfTimes, runningLv);
countDownTimer.run();
baseAdapter.notifyDataSetChanged();
更新:这是 onCreateView,我想重用视图
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = null;
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null) {
parent.removeView(view);
}
} else {
view = inflater.inflate(R.layout.fragment_running, null);
setupViewItems(view);
}
return view;
}