Android: Multiple simultaneous count-down timers in a ListView

前端 未结 4 634
说谎
说谎 2020-12-30 08:12

I am creating an app that requires a ListView with an undetermined number of elements, each of which has a timer that counts down from a variable number. I am able to succes

4条回答
  •  长情又很酷
    2020-12-30 08:21

    Here is another solution of using ListView with multiple CountDownTimer. Firstly, we create a class MyCustomTimer that holds the CountDownTimer:

    public class MyCustomTimer{
        public MyCustomTimer() {
        }
        public void setTimer(TextView tv, long time) {
            new CountDownTimer(time, 1000) {
                public void onTick(long millisUntilFinished) {
                    //Set formatted date to your TextView
                    tv.setText(millisUntilFinished);
                }
                public void onFinish() {
                    tv.setText("Done!");
                }
            }.start();
        }
    }
    

    Then, initilize the created class in your adapter:

    public class MyAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private MyCustomTimer myTimer;
        private ArrayList myItems;
    
        public MyAdapter(Context context, ArrayList data) {
            mInflater = LayoutInflater.from(context);
            myTimer= new MyCustomTimer();
            myItems = data;
        }
    
        //... implementation of other methods
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = mInflater.inflate(R.layout.listview_row, null);
            TextView tvTimer = (TextView) convertView.findViewById(R.id.textview_timer);
            TextView tvName = (TextView) convertView.findViewById(R.id.textview_name);
    
            Item item = data.get(position);
    
            tvName.setText(item.getName());
            myTimer.setTimer(tvTimer, item.getTime());
    
            return convertView;
        }
    }
    

提交回复
热议问题