Edición
Buscando más soluciones que no acaban de funcionar bien, ya que crean fugas de memoria etc.. he encontrado ese componente https://github.com/curioustechizen/android-ago Funciona perfectamente en un recyclerview, falta comprobación de sobrecarga de items 1000 items para determinar si va fino o no.
Su implementación:
<com.github.curioustechizen.ago.RelativeTimeTextView
android:id="@+id/timestamp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:relative_time_prefix="Completed "
android:layout_marginTop="@dimen/margin_primary" />
Asignación de un tiempo previo en guardado onBindViewHolder
if (item.getLastChecked() != null)
holder.mSummary.setReferenceTime(item.getLastChecked().getTime());
else
//sin tiempo especificado
Anterior
Siguiendo ese ejemplo: https://github.com/Manikkumar1988/TimerInRecyclerView
He creado una clase UpdateTimerThread
que implementa Runnable
public class UpdateTimerThread implements Runnable {
private static final String TAG = UpdateTimerThread.class.getSimpleName();
public TextView holder;
Handler handler;
public UpdateTimerThread(Handler handler, TextView holder) {
Log.d(TAG, "CREATE UpdateTimerThread: ");
this.handler = handler;
this.holder = holder;
}
@Override
public void run() {
/* do what you need to do */
Date date = new Date();
String stringDate = DateFormat.getDateTimeInstance().format(date);
holder.setText(stringDate);
Log.d(TAG, stringDate);
handler.postDelayed(this, 100);
}
}
Luego en la asignación del ViewHolder
es donde se inicia el contador
public class SimpleListAdapter
extends RecyclerView.Adapter<SimpleListAdapter.ViewHolder> {
...
private Handler handler = new Handler();
...
public class ViewHolder extends RecyclerView.ViewHolder {
...
UpdateTimerThread customRunnable;
...
public ViewHolder(View v) {
super(v);
customRunnable = new UpdateTimerThread(handler,mSummary);
handler.postDelayed(customRunnable, 100);
}
Crear función para finalizar los contadores al pausar la actividad
public void clearAll() {
handler.removeCallbacksAndMessages(null);
}
En el Activity
@Override
protected void onPause() {
super.onPause();
mAdapter.clearAll();
}
Problemas que detecto: que ejecuta un hilo por cada elemento que se visualice, sin hace caso que si se destruye pare el contador, es decir si tienes 1000 items y vas recorriendo por la lista, se ejecuta un hilo para cada item que se ha mostrado, solo cuando giras el terminal es cuando los elimina.
Si se elimina un item, pues sigue allí su hilo de ejecutación