我有一个 ListView ,想要对每个项目进行倒计时。我的问题是,当我滚动倒计时时间时跳转到不正确的项目(因此它显示另一个项目倒计时时间)并且没有任何押韵或理由?这是代码
private final Map<String, TextView> mcounterlist= new HashMap<String, TextView>();
然后在我的适配器上的 getview 中我这样做
String gmtFormat = "yyyy-MM-dd HH:mm:ss";
TimeZone tz = TimeZone.getDefault();
SimpleDateFormat sdf = new SimpleDateFormat(gmtFormat);
sdf.setTimeZone(tz);
Date dd = null;
try {
dd = sdf.parse(o.endAt);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Date now = new Date();
String sss = timeCalculate((dd.getTime() /1000)- (now.getTime() /1000) );
ea.setText("Time Left: " + sss);
TextView cdi = new TextView();
mcounterlist.put(o.id , cdi);
所以此时我只是运行一个重复线程来更新。
private final Runnable mRunnable = new Runnable() {
public void run() {
// TextView textView;
String gmtFormat = "yyyy-MM-dd HH:mm:ss";
TimeZone tz = TimeZone.getDefault() ;
SimpleDateFormat sdf = new SimpleDateFormat(gmtFormat);
sdf.setTimeZone(tz);
// if counters are active
if(mcounterlist.size() > 0)
{
for (int i = 0; i < m_orders.size() && i < mcounterlist.size() ;i++) {
Order o = m_orders.get(i);
TextView c = mcounterlist.get(o.id);
Date dd = null;
try {
dd = sdf.parse(o.endAt);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Date now = new Date();
long l = (dd.getTime() /1000)- (now.getTime() /1000);
String sss;
if (l < 0)
{
sss = "ENDED";
}
else
{
sss = timeCalculate(l);
}
if(l < 60 * 60 * 24)
{
c.setBackgroundColor(Color.parseColor("#E3170D"));
}
else
{
c.setBackgroundColor(Color.parseColor("#00000000"));
}
c.setText("Time Left: " + sss);
}
}
mHandler.postDelayed(this, 1000);
}
};
但是当我滚动列表时, TextView 跳得到处都是。我相信我的部分问题与我每 30 秒对列表进行排序的方式有关,但项目的 ID 不会改变。有什么明显的错误吗?
谢谢。
最佳答案
所以问题是 ListView 中的 View 被重用,解决方案是实现以下将 id 更改为我的 HashMap 中的位置并将其放入 GETVIEW
mcounterlist.remove(position);
mcounterlist.put(position , ea);
您可能不需要删除该位置,但我把它留在那里,因为我花了一个小时在这上面,而且它有效,所以我不想改变任何东西:)
然后在我的重复任务中,我需要排除任何不可见的项目,所以这是我的处理程序代码
int fp = lv.getFirstVisiblePosition() -1 < 0 ? 0 :lv.getFirstVisiblePosition() -1;
int lp = lv.getLastVisiblePosition();
for (int i = fp; i < mcounterlist.size() && i < lp;i++) {
//Log.i("TEST231231",String.valueOf(i));
if (i < lv.getFirstVisiblePosition() -1 )
{
continue;
}
if (i >= lv.getLastVisiblePosition())
{
continue;
}
//my adapter list
Order o = m_orders.get(i);
//since I set the position as the refereance, I can use that for the hashmap
TextView c = mcounterlist.get(i);
...
因此,本质上,由于相同的 TextView 被回收,我无法更新所有这些 TextView ,因为不在列表中的项目正在共享 Activity 文本框。为了消除此问题,我检查并仅编辑可见项目的文本框。
关于java - Android Listview 倒计时器导致奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12242895/