¿Cómo comprobar si mi ListView tiene número desplazable de artículos?

¿Cómo saber si su ListView tiene suficiente número de elementos para que pueda desplazarse?

Por ejemplo, si tengo 5 elementos en mi ListView todo se mostrará en una sola pantalla. Pero si tengo 7 o más, mi ListView empieza a desplazarse. ¿Cómo sé si mi Lista puede desplazarse por programa?

La respuesta de Diegosan no puede diferenciar cuando el último elemento es parcialmente visible en la pantalla. Aquí hay una solución a ese problema.

Primero, el ListView debe ser representado en la pantalla antes de que podamos comprobar si su contenido es desplazable. Esto se puede hacer con un ViewTreeObserver:

 ViewTreeObserver observer = listView.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (willMyListScroll()) { // Do something } } }); 

Y aquí está willMyListScroll() :

 boolean willMyListScroll() { int pos = listView.getLastVisiblePosition(); if (listView.getChildAt(pos).getBottom() > listView.getHeight()) { return true; } else { return false; } } 

Según mi comentario sobre la respuesta de Mike Ortiz, creo que su respuesta es incorrecta:

getChildAt () sólo cuenta los niños que son visibles en la pantalla. Mientras tanto, getLastVisiblePosition devuelve el índice basado en el adaptador. Así que si la últimaPreguntaVisible es 8 porque es el 9º elemento de la lista y sólo hay 4 elementos visibles en la pantalla, vas a tener un accidente. Compruébelo llamando a getChildCount () y vea. Los índices para getChildAt no son los mismos que los índices para el conjunto de datos. Compruebe esto: ListView getChildAt devolver null para los niños visibles

Aquí está mi solución:

 public boolean isScrollable() { int last = listView.getChildCount()-1; //last visible listitem view if (listView.getChildAt(last).getBottom()>listView.getHeight() || listView.getChildAt(0).getTop()<0) { //either the first visible list item is cutoff or the last is cutoff return true; } else{ if (listView.getChildCount()==listView.getCount()) { //all visible listitem views are all the items there are (nowhere to scroll) return false; } else{ //no listitem views are cut off but there are other listitem views to scroll to return true; } } } 

No se puede detectar esto antes de que android renderizar la pantalla con el listView . Sin embargo, puede detectar absolutamente este post-procesamiento.

 boolean willMyListScroll() { if(listView.getLastVisiblePosition() + 1 == listView.getCount()) { return false; } return true; } 

Lo que esto hace es comprobar si la ventana visible listView contiene TODOS los elementos de la vista de lista. Si puede, entonces el listView nunca se desplazará y el getLastVisiblePosition() siempre será igual al número total de elementos en el dataAdapter de la lista.

Este es el código que escribí para mostrar una imagen después de la última fila de la lista:

 public class ShowTheEndListview { private ImageView the_end_view; private TabbedFragRootLayout main_layout; private ListView listView; private float pas; private float the_end_img_height; private int has_scroll = -1; public ShowTheEndListview(float height) { the_end_img_height = height; pas = 100 / the_end_img_height; } public void setData(ImageView the_end_view, TabbedFragRootLayout main_layout, ListView listView) { this.the_end_view = the_end_view; this.main_layout = main_layout; this.listView = listView; } public void onScroll(int totalItemCount) { if(totalItemCount - 1 == listView.getLastVisiblePosition()) { int pos = totalItemCount - listView.getFirstVisiblePosition() - 1; View last_item = listView.getChildAt(pos); if (last_item != null) { if(listHasScroll(last_item)) { // Log.e(TAG, "listHasScroll TRUE"); } else { // Log.e(TAG, "listHasScroll FALSE"); } } } } private boolean listHasScroll(View last_item) { if(-1 == has_scroll) { has_scroll = last_item.getBottom() > (main_layout.getBottom() - the_end_img_height - 5) ? 1 : 0; } return has_scroll == 1; } public void resetHasScroll() { has_scroll = -1; } } 

AbsListView incluye lo siguiente:

 /** * Check if the items in the list can be scrolled in a certain direction. * * @param direction Negative to check scrolling up, positive to check scrolling down. * @return true if the list can be scrolled in the specified direction, false otherwise. * @see #scrollListBy(int) */ public boolean canScrollList(int direction); 

Necesitas reemplazar layoutChildren () y usarlo dentro de eso:

 @Override protected void layoutChildren() { super.layoutChildren(); isAtBottom = !canScrollList(1); isAtTop = !canScrollList(-1); } 

Así es como yo solía comprobar

 if (listView.getAdapter() != null && listView.getLastVisiblePosition() == listView.getAdapter().getCount() - 1 && listView.getChildAt(listView.getChildCount() - 1).getBottom() == listView.getBottom()) 

si da verdadero, entonces la lista está en la parte inferior

Utilice el setOnScrollListener , aplicando la devolución de llamada a OnScrollListener , puede determinar si se está realizando el desplazamiento utilizando las constantes predefinidas y manejar la situación en consecuencia.

  boolean listBiggerThanWindow = appHeight - 50 <= mListView.getHeight(); Toast.makeText(HomeActivity.this, "list view bigger that window? " + listBiggerThanWindow, Toast.LENGTH_LONG) .show(); if (listBiggerThanWindow) { // do your thing here... } 

puede obtener dimensiones en onCreate () llamando a post (Runnable) en View.

  • A veces listView.getChildAt (int index) devuelve NULL (Android)
  • ¿Cómo aplicar una transparencia (enfoque?) Al pulsar cualquier elemento (como lo hace Google)?
  • Android: Eliminación de elementos de una actividad ListView / ArrayAdapter
  • Android - SwipeRefreshLayout con texto vacío
  • ¿Cuál es la diferencia entre ListView, AbsListView y RecyclerView
  • Estoy utilizando el listview añadir / quitar pie de página para listview cross app en android versión 4.3?
  • ExpandableListview Como TreeView Android
  • Filtrado ListView que forma parte de un fragmento de ViewPager
  • ¿Cómo evitar un doble toque en un ListView?
  • Listview con inflación de diseño diferente para cada fila
  • Elemento de fila personalizada de Android para ListView
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.