Eliminar lista de elementos con Diapositiva, como Gmail

Estoy desarrollando una aplicación con una lista de tiendas en un listview. Necesito que cuando deslizo el elemento de listview a la derecha (o izquierda), este elemento debe ser eliminado de la lista.

Tengo mi listview y solo necesito la función para hacerlo.

Gracias por adelantado.

Así es como me doy cuenta de este efecto. Tenemos un ListView lvSimple y añadimos onTouchListener a nuestro lvSimple . Este es mi código de trabajo.

 float historicX = Float.NaN, historicY = Float.NaN; static final int DELTA = 50; enum Direction {LEFT, RIGHT;} ... ListView lvSimple = (ListView) findViewById(R.id.linLayout); ... lvSimple.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: historicX = event.getX(); historicY = event.getY(); break; case MotionEvent.ACTION_UP: if (event.getX() - historicX < -DELTA) { FunctionDeleteRowWhenSlidingLeft(); return true; } else if (event.getX() - historicX > DELTA) { FunctionDeleteRowWhenSlidingRight(); return true; } break; default: return false; } return false; } }); 

Donde la función FunctionDeleteRowWhenSlidingLeft() está llamando cuando cuando deslizamos a la izquierda, FunctionDeleteRowWhenSlidingRight() – a la derecha, respectivamente. En esta función es necesario pegar código para la animación.

Respuesta de Android-Developer señala el código de Roman Nurik en gist.github.com . Este código está desactualizado. Utiliza este deslizador para despedir al oyente en su proyecto de origen abierto Dash Clock .

Hay algunas cosas que usted debe saber, antes de usar el código en Gist.github.com.

  1. El código obsoleto en Gist.Github es muy sensible a los toques. Si sigue tocando un elemento en el ListView, se eliminará. En el código actualizado fijó la sensibilidad del lanzamiento.
  2. Este oyente no funciona bien si tiene divisores declarados en ListView. Si desea divisores, declárelos en el diseño de ListItem.
  3. Este código está todavía en versión beta . Caveat emptor.

Así que recomiendo usar el código actualizado. Puede encontrar la fuente actualizada aquí .

Otra opción que debe considerar es utilizar la biblioteca EnhancedListView de Tim Roes. [Actualización – 1/8/2015] Con la introducción de RecycleView, esta biblioteca ha quedado obsoleta.

El escuchador de Nurik Roman Nurik mencionado anteriormente requiere un nivel de API 12 o superior. Jake Wharton portado este código para apoyar todos los niveles de API en SwipeToDismissNOA .

Tim Roes extendió esta biblioteca más para apoyar la función Deshacer .

Hice una respuesta usando lo que macloving escribió. Por ahora está trabajando, pero es sólo trabajo si todos sus hijos tienen la misma altura.

 listView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub switch (event.getAction()) { case MotionEvent.ACTION_DOWN: historicX = event.getX(); historicY = event.getY(); return false; case MotionEvent.ACTION_UP: if (listView.getChildAt(0) != null) { int heightOfEachItem = haveListView.getChildAt(0).getHeight(); int heightOfFirstItem = -haveListView.getChildAt(0).getTop() + haveListView.getFirstVisiblePosition()*heightOfEachItem; //IF YOU HAVE CHILDS IN LIST VIEW YOU START COUNTING //listView.getChildAt(0).getTop() will see top of child showed in screen //Dividing by height of view, you get how many views are not in the screen //It needs to be Math.ceil in this case because it sometimes only shows part of last view final int firstPosition = (int) Math.ceil(heightOfFirstItem / heightOfEachItem); // This is the same as child #0 //Here you get your List position, use historic Y to get where the user went first final int wantedPosition = (int) Math.floor((historicY - haveListView.getChildAt(0).getTop()) / heightOfEachItem) + firstPosition; //Here you get the actually position in the screen final int wantedChild = wantedPosition - firstPosition; //Depending on delta, go right or left if (event.getX() - historicX < -DELTA) { //If something went wrong, we stop it now if (wantedChild < 0 || wantedChild >= List.size()|| wantedChild >= listView.getChildCount()) { return true; } //Start animation with 500 miliseconds of time listView.getChildAt(wantedChild).startAnimation(outToLeftAnimation(500)); //after 500 miliseconds remove from List the item and update the adapter. new java.util.Timer().schedule( new java.util.TimerTask() { @Override public void run() { List.remove(wantedPosition); updateAdapter(); } }, 500 ); return true; } else if (event.getX() - historicX > DELTA) { //If something went wrong, we stop it now if (wantedChild < 0 || wantedChild >= List.size() || wantedChild >= listView.getChildCount()) { return true; } //Start animation with 500 miliseconds of time listView.getChildAt(wantedChild).startAnimation(outToRightAnimation(500)); //after 500 miliseconds remove from List the item and update the adapter. new java.util.Timer().schedule( new java.util.TimerTask() { @Override public void run() { List.remove(wantedPosition); updateAdapter(); } }, 500 ); return true; } } return true; default: return false; } } }); 

Las animaciones tienen esta función:

 private Animation outToLeftAnimation(int duration) { Animation outtoLeft = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f); outtoLeft.setDuration(duration); outtoLeft.setInterpolator(new AccelerateInterpolator()); return outtoLeft; } private Animation outToRightAnimation(int duration) { Animation outtoRight = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f); outtoRight.setDuration(duration); outtoRight.setInterpolator(new AccelerateInterpolator()); return outtoRight; } 

Estoy tratando esto, y hasta ahora no he visto errores, si alguien podría intentar también sería bueno.

  • Pie de página debajo de la vista de lista fija en la parte inferior de la pantalla
  • ¿Cómo manejar el scroller rápido en Lollipop 5.1?
  • ¿Cómo abrir una nueva actividad haciendo clic en un elemento de listview?
  • ListView elemento de animación de desplazamiento ("UIKit Dynamics" -como)
  • No se puede encontrar el recurso, No se identifica el elemento que falta
  • Android: diseño predeterminado para listitem que contiene el título y el subtítulo
  • Mostrar divisor después del último elemento de la lista
  • Cómo obtener redes wifi disponibles y mostrarlas en una lista en android
  • Pinch Android y Zoom de la imagen en la actividad
  • Listview con inflación de diseño diferente para cada fila
  • Ocultar fila de ListView sin ocupar espacio
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.