CountDownTimer问题Listview Android

时间:2013-07-31 06:50:34

标签: android listview countdowntimer

我创建了一个带倒数计时器的列表视图,结果在第一次显示效果很好但是当滚动列表时它会被洗牌并且结果出错。

适配器类:

public class EventsListAdapter extends BaseAdapter {

    LayoutInflater inflater;
    Activity context;

    List<MyEvents> list;

    long startTime = 0L;
    long countUp;
    String hrs = "00";
    String mins = "00";
    String secs = "00";
    private MyCustomTimer myTimer;
    public EventsListAdapter(Activity context, List<MyEvents> list) {
        this.context = context;
        inflater = context.getLayoutInflater();
        this.list = list;
    }

    public void setActivityList(List<MyEvents> LoadList) {
        list = LoadList;
    }

    public int getCount() {
        return list.size();
    }

    public Object getItem(int position) {
        return list.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    static class ViewHolder {
        TextView name;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        MyEvents eventsData = list.get(position);   

        View rowView = convertView;
        ViewHolder viewHolder;
        if (rowView == null) {
            LayoutInflater inflater = context.getLayoutInflater();
            rowView = inflater.inflate(R.layout.likes_inflate, null);
            viewHolder = new ViewHolder();
            viewHolder.name = (TextView) rowView.findViewById(R.id.lblName);
            if (eventsData.isStarted()){
                myTimer = new MyCustomTimer(viewHolder.name);
                myTimer.setTimer(eventsData.start_date);
            }
            rowView.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) rowView.getTag();
        }

        return rowView;
    }
}

CountDownTimer类:

class MyCustomTimer{
        TextView tv;
        public MyCustomTimer(TextView tv) {
            this.tv = tv;
        }

        void setTimer(final long time) {
            new CountDownTimer(time, 1000) {
                public void onTick(long millisUntilFinished) {
                    //Set formatted date to your TextView                   
                    tv.setText(Utilities.getDurationBreakdown(millisUntilFinished));

                }
                public void onFinish() {
                    tv.setText("Done!");
                }
            }.start();
        }
    }

这段代码有问题吗?请建议。

2 个答案:

答案 0 :(得分:0)

滚动列表视图时,会调用getView()。所以柜台又开始了。在哈希映射等变量中维护计数器。在getView()中检查此变量,然后根据它设置计数器的值。

答案 1 :(得分:-1)

您可以在https://stackoverflow.com/a/53543180/6711554处查看我的答案。我使用过RecyclerView,但您可以为ListView做同样的事情。