1

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

适配器类:

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();
        }
    }

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

4

2 回答 2

0

每当您滚动列表视图时,都会调用 getView()。所以计数器又开始了。将计数器维护在哈希映射之类的变量中。在 getView() 中检查这个变量,然后根据它设置计数器的值。

于 2013-07-31T06:56:35.580 回答
-1

你可以在这里查看我的答案https://stackoverflow.com/a/53543180/6711554。我用过RecyclerView,但你可以对ListView.

于 2018-11-29T16:28:48.940 回答