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.
- Cómo implementar gridlayoutmanager horizontal
- Cómo establecer la altura de una fila de elementos en GridLayoutManager
- Centrar elementos en un RecyclerView cuando se implementa con GridLayoutManager
- Cómo hacer que RecyclerView se desplace sin problemas?
- Recycler View Con Gridlayout Manager
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?
- ¿Cómo puedo llenar RecyclerView con GridLayoutManager de derecha a izquierda
- RecyclerView con GridLayoutManager intentando resolver wrap_content
- Cargando diferentes imágenes fuera de línea (imágenes predeterminadas) en NetworkImageview Volley android
- Custom GridlayoutManager para WRAP_CONTENT en un RecyclerView
- Las animaciones de elementos predictivos de RecyclerView no funcionan (APPEARING)
- Recyclerview vincula todas las vistas al mismo tiempo
- Diseño cuadrado en GridLayoutManager para RecyclerView
- Aplicar offset a elementos GridLayout y conservar el mismo tamaño entre todos los elementos
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 } }
- ¿Cuál es el ciclo de vida de una variable pública estática en Android?
- Android – no puede poner el pulgar en el centro de una barra de búsqueda