Android: Multiple simultaneous count-down timers in a ListView

前端 未结 4 625
说谎
说谎 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:24

    Please have a look here at my blog where you will find an example on how to achieve this.

    One solution is to put the TextView that represents each counter into a HashMap together with it's position in the list as the key.

    In getView()

    TextView counter = (TextView) v.findViewById(R.id.myTextViewTwo);
    if (counter != null) {
        counter.setText(myData.getCountAsString());
        // add the TextView for the counter to the HashMap.
        mCounterList.put(position, counter);
    }
    

    Then you can update the counters by using a Handler and where you post a runnable.

    private final Runnable mRunnable = new Runnable() {
        public void run() {
            MyData myData;
            TextView textView;
    
            // if counters are active
            if (mCountersActive) {                
                if (mCounterList != null && mDataList != null) {
                    for (int i=0; i < mDataList.size(); i++) {
                        myData = mDataList.get(i);
                        textView = mCounterList.get(i);
                        if (textView != null) {
                            if (myData.getCount() >= 0) {
                                textView.setText(myData.getCountAsString());
                                myData.reduceCount();
                            }
                        }
                    }
                }
                // update every second
                mHandler.postDelayed(this, 1000);
            }
        }
    };
    

提交回复
热议问题