Android: Actualizar ListView Items cada 1 minuto

Tengo un ListView de encargo en mi uso, conteniendo un ImageView y 3-5 TextViews.

1 de los TextViews muestra el intervalo de tiempo entre la hora actual y la hora especificada para ese elemento ListView.

Me gusta: Publicado hace 1 hora

La pregunta es, ¿cómo puedo actualizar este TextView cada minuto sin ninguna perturbación para el ListView.

Como: si estoy mirando el ListView por 5 minutos, sólo este TextView solo debe cambiar de 1 minuto a 2 minutos por lo que para cada elemento visible

Lo que intenté:

  1. Establecer este TextView en getView () utilizando System.currentTimeMillis() - givenTime[position];

Pero aquí el TextView no se actualizará si no estoy desplazando (no llamando al getView) o cambiando la visibilidad de los artículos.

  1. Utilice un thread timeTask () cada 1 minuto e intente actualizar el TextView de cada elemento

Aquí el problema es conseguir una Excepción:

 android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 

Además no tengo idea de cómo cambiar el TextView para cada elemento ListView de la actividad.

Pero esto parece un caso familiar.

¿Cómo puedo conseguir esto?

Gracias

Utilice un postDelayed y su método postDelayed para invalidar el adaptador de la lista de la siguiente manera:

 final Handler handler = new Handler() handler.postDelayed( new Runnable() { @Override public void run() { adapter.notifyDataSetChanged(); handler.postDelayed( this, 60 * 1000 ); } }, 60 * 1000 ); 

Sólo debe actualizar la interfaz de usuario en el subproceso principal (UI).

Al crear el controlador en el subproceso principal, asegúrese de que todo lo que publica en el controlador se ejecuta en el subproceso principal también.

Utilice el construido en TimerTask

http://developer.android.com/reference/java/util/TimerTask.html

Esta es una forma sólida de hacer las cosas.

También puede crear personalizado TextView que se actualiza cada segundo o minuto o hora. Esto se puede hacer fácilmente creando una clase que extienda TextView y agregue el TextView dentro de esa clase. Los beneficios son que usted no tiene que actualizar todo su ListView, TextView se actualizará automáticamente.

Ejemplo:

 public class TextViewTimeCounter extends TextView { private long mStartTime = 0; private long mTimeNow = 0; private int mDelay = 0; private String mPart1 = ""; private String mPart2 = ""; private Handler mHandler; public TextViewTimeCounter(Context context) { super(context, null, 0); } public TextViewTimeCounter(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TextViewTimeCounter(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void startTimer(long delay, String part1, String part2){ mStartTime = System.currentTimeMillis(); mTimeNow = System.currentTimeMillis(); mDelay = delay; mHandler = new Handler(); mHandler.postDelayed(r, delay); convertDatesToMinutes(mStartTime, mTimeNow); } public void stopTimer(){ if(mHandler != null){ mHandler = null; mStartTime = 0; mTimeNow = 0; } } public boolean isTimerRunning(){ return mHandler == null? false : true; } Runnable r = new Runnable() { @Override public void run(){ mTimeNow += mDelay; convertDatesToMinutes(mStartTime, mTimeNow); if(mHandler != null){ mHandler.postDelayed(r, mDelay); } } }; public void convertDatesToMinutes(long start, long end){ long secs = (end - start); long minute = (secs / (1000 * 60)) % 60; long hour = (secs / (1000 * 60 * 60)) % 24; String time = String.format(Locale.getDefault(), "%2d hours %2d minutes", hour, minute); setText(mPart1 + time + mPart2); } 

Uso:

 TextViewTimeCounter timer = (TextViewTimeCounter)convertView.findViewById(R.id.start_logging_time_text); timer.startTimer(10000, "Posted ", " ago"); 

La salida se verá así:

  Posted 1 hours 5 minutes ago 

Si desea mostrar segundos también, cambie el convertDatesToMinutes(long start, long end) a esto:

 public void convertDatesToMinutes(long start, long end){ long secs = (end - start); long second = (secs / 1000) % 60; long minute = (secs / (1000 * 60)) % 60; long hour = (secs / (1000 * 60 * 60)) % 24; String time = String.format(Locale.getDefault(), "%2d hours %2d minutes %2d seconds", hour, minute, second); setText(mPart1 + time + mPart2); } 

Si desea repetir una acción en el hilo principal en fracciones de tiempo, debe utilizar el método "schedule" de la clase Time.class

 mHandler = new Handler(); mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { mHandler.post(new Runnable() { @Override public void run() { // run main thread code } }); } }, DELAY_TIME, PERIOD_TIME); 
  • Vista personalizada vacía en ListView android
  • Aparece una imagen incorrecta en mis filas ListView
  • Todavía otro getView llamado varias veces
  • Cómo configurar onContextItemClickListener para un menú contextual de ListView?
  • Android: ¿qué hace el método "setTextFilterEnabled"?
  • Cómo puede mostrar un AdView en cada n-ésima posición en un listView
  • ListView no aparece en MainActivty de mi aplicación (una imagen adjunta)
  • ¿Hay una manera de desactivar la animación de Android ListView?
  • Conversación por SMS
  • Control del color del borde de atenuación en ListViews
  • CursorAdapter en ListView
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.