Android: StaggeredGridLayoutManager se desplaza hacia arriba mientras se inicializa

Estoy utilizando StaggeredGridLayoutManager para mi galería de imágenes. He establecido setReverseLayout(true) , para que las imágenes se apilan desde la parte inferior.

El problema que estoy enfrentando es que en la inicialización de la aplicación, los puntos de desplazamiento en la parte inferior de la galería. Quisiera que el pergamino estuviera en la parte superior de la galería cuando el usuario primero inicie la aplicación.

He intentado usar scrollToPosition (el fragmento de código siguiente), pero luego el rollo termina en algún lugar en medio de la galería, probablemente porque las imágenes no se han cargado correctamente en el momento de llamar a scrollToPosition .

 mLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL); mLayoutManager.setReverseLayout(true); mRecyclerView.setLayoutManager(mLayoutManager); mImageList = ((MainActivity)getActivity()).getImages(); adapter = new ImageAdapter(getActivity(),mImageList); mRecyclerView.setAdapter(adapter); mRecyclerView.scrollToPosition(mImageList.size()-1); 

¿Hay una manera adecuada de apuntar el rollo en la parte superior, en lugar de en la parte inferior?

He resuelto el problema similar antes y aquí es el método:

 mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @Override public void onGlobalLayout() { ViewTreeObserver observer = mRecyclerView.getViewTreeObserver(); scrollRecyclerViewToTop(); if (!observer.isAlive()) { return; } if (mScrolledByUser) { if (hasJellyBeanApi()) { observer.removeOnGlobalLayoutListener(this); } else { observer.removeGlobalOnLayoutListener(this); } } } }); 

Y:

 mRecyclerView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { mScrollByUser = true; return false; } }); 

Y:

 private void scrollRecyclerViewToTop() { mRecyclerView.scrollToPosition(0); mRecyclerView.scrollBy(0, Integer.MIN_VALUE); } 

El significado es fácil: deje que RecyclerView se desplace siempre hasta la parte superior hasta que el usuario lo toque. Espero que esto le pueda ayudar.

Intente encontrar la primera posición visible llamando a findFirstCompletelyVisibleItemPositions

O findFirstVisibleItemPositions

La llamada a su reciclador ver scrollToPosition con la posición obtenida del (los) método (s) anterior (es)

He utilizado scrolltoposition dentro de dataobserver y ahora funciona bien ..

Cuando la carga de recyclerview, los elementos en la parte superior son visibles con el siguiente código:

 rcAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onItemRangeInserted(int positionStart, int itemCount) { super.onItemRangeInserted(positionStart, itemCount); int count = rcAdapter.getItemCount(); mRecyclerView.scrollToPosition(itemCount-1); } }); 

Para desplazarse a la parte inferior de los elementos recién agregados como en la vista de chat, utilice el código a continuación.

  rcAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onItemRangeInserted(int positionStart, int itemCount) { super.onItemRangeInserted(positionStart, itemCount); int count = rcAdapter.getItemCount(); int lastVisiblePositions[] = new int[2]; //for 2 columns int lastVisiblePosition = staggeredGridLayoutManager.findLastCompletelyVisibleItemPositions(lastVisiblePositions)[0]; // If the recycler view is initially being loaded or the user is at the bottom of the list, scroll // to the bottom of the list to show the newly added message. if (lastVisiblePosition == -1 || (positionStart >= (count- 1) && lastVisiblePosition == (positionStart - 1))) { mRecyclerView.scrollToPosition(positionStart); } } }); 

Intente usar la función scrollToPositionWithOffset() de StaggeredGridLayoutManager . Lo encontré más confiable que scrollToPosition . También asegúrese de ejecutar esta función dentro de Handler().post() . Esto hará que el Runnable se agregue a la cola de mensajes. Se ejecutará una vez que el hilo de interfaz de usuario esté libre.

 new Handler().post(new Runnable() { @Override public void run() { staggeredGridLayoutManager.scrollToPositionWithOffset(mImageList.size() - 1, 0); } }); 

Este código puede ayudarte, yo también usé este enlace en código

https://guides.codepath.com/android/Endless-Scrolling-with-AdapterViews-and-RecyclerView

Cada AdapterView (como ListView y GridView) tiene soporte para enlazar a los eventos OnScrollListener que se activan cada vez que el usuario se desplaza a través de la colección. Usando este sistema, podemos definir un EndlessScrollListener básico que soporta la mayoría de casos de uso creando nuestra propia clase que extiende OnScrollListener:

 public abstract class EndlessScrollListener implements AbsListView.OnScrollListener { // The minimum number of items to have below your current scroll position // before loading more. private int visibleThreshold = 5; // The current offset index of data you have loaded private int currentPage = 0; // The total number of items in the dataset after the last load private int previousTotalItemCount = 0; // True if we are still waiting for the last set of data to load. private boolean loading = true; // Sets the starting page index private int startingPageIndex = 0; public EndlessScrollListener() { } public EndlessScrollListener(int visibleThreshold) { this.visibleThreshold = visibleThreshold; } public EndlessScrollListener(int visibleThreshold, int startPage) { this.visibleThreshold = visibleThreshold; this.startingPageIndex = startPage; this.currentPage = startPage; } // This happens many times a second during a scroll, so be wary of the code you place here. // We are given a few useful parameters to help us work out if we need to load some more data, // but first we check if we are waiting for the previous load to finish. @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // If the total item count is zero and the previous isn't, assume the // list is invalidated and should be reset back to initial state if (totalItemCount < previousTotalItemCount) { this.currentPage = this.startingPageIndex; this.previousTotalItemCount = totalItemCount; if (totalItemCount == 0) { this.loading = true; } } // If it's still loading, we check to see if the dataset count has // changed, if so we conclude it has finished loading and update the current page // number and total item count. if (loading && (totalItemCount > previousTotalItemCount)) { loading = false; previousTotalItemCount = totalItemCount; currentPage++; } // If it isn't currently loading, we check to see if we have breached // the visibleThreshold and need to reload more data. // If we do need to reload some more data, we execute onLoadMore to fetch the data. if (!loading && (firstVisibleItem + visibleItemCount + visibleThreshold) >= totalItemCount ) { loading = onLoadMore(currentPage + 1, totalItemCount); } } // Defines the process for actually loading more data based on page // Returns true if more data is being loaded; returns false if there is no more data to load. public abstract boolean onLoadMore(int page, int totalItemsCount); @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // Don't take any action on changed } } 
  • Android agrega espaciado debajo del último elemento en recyclerview con gridlayoutmanager
  • Recycler View con múltiples filas y columnas - AutoFit como Flow Layout
  • RecyclerView con GridLayoutManager
  • Establecer el intervalo de elementos en GridLayoutManager mediante SpanSizeLookup
  • RecyclerView - elementos de pantalla que saltan el primer pase de diseño
  • Arrastrar y soltar vista fuera de Recyclerview
  • RecyclerView GridLayoutManager con el encabezado de ancho completo
  • Horizontalmente en RecyclerView (con GridLayoutManager)
  • Android GridLayoutManager con columnas y fila span
  • RecyclerView wrap_content con GridLayoutManager
  • Diferentes elementos (dinámicos) de altura en GridLayoutManager
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.