Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Found a clean solution (if someone needs something like that). I needed to update a TextView to set the new counter value (every second). </p> <p>In BaseAdapters getView I add the TextViews(s) to a WeakHashMap. The TextView is the key of the map. A key/value mapping will be removed if the key is no longer referenced. So I do not cause memory leaks. The GarbageCollector does the work.</p> <p>A thread counts "counter objects" down and refreshes the TextViews with the corresponding values (GarbageCollector runs all the time so in my case the map consists mostly of 3 items because the gallery shows just one item. Due to GarbageCollection the map gets immediately cleared by "unused" TextViews specially when scrolling fast through the list/gallery)</p> <p>BaseAdapter's getView():</p> <pre><code>private WeakHashMap&lt;TextView, Integer&gt; counterMap = new WeakHashMap&lt;TextView,Integer&gt;(); private Handler counterHandler = new Handler(); public View getView(...) { //... counterMap.put(holder.tvCounter, position); //... } </code></pre> <p>The counter:</p> <pre><code>// Thread decrementing the time of the counter objects and updating the UI private final Runnable counterTimeTask = new Runnable() { public void run() { //... // decrement the remaining time of all objects for (CounterData data : counterDataList) data.decrementTimeLeftInSeconds(); // iterate through the map and update the containing TextViews for (Map.Entry&lt;TextView, Integer&gt; entry : counterMap.entrySet()) { TextView tvCounter = entry.getKey(); Integer position = entry.getValue(); CounterData data = counterDataList.get(position); long timeLeftInSeconds = data.getTimeLeftInSeconds(); tvCounter.setText(" " + timeLeftInSeconds); } if (yourCondition) counterHandler.postDelayed(this, 1000); } }; </code></pre> <p>Start/stop the counter:</p> <pre><code>public void startCounter() { counterHandler.post(counterTimeTask); } public void stopCounter() { counterHandler.removeCallbacks(counterTimeTask); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload