GridView com infinita rolagem otimização

Mr. Wolodyjowsky:

Eu criei um aplicativo simples que obtém imagens de Pixabay e as exibirá em uma GridViewcom rolagem infinita.

meu OnScrollListener:

public class BasicOnScrollListener implements AbsListView.OnScrollListener {

private IOnScroll onScroll;

public BasicOnScrollListener(IOnScroll action) {
    this.onScroll = action;
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    if (firstVisibleItem + visibleItemCount >= totalItemCount - visibleItemCount)
        onScroll.onReachedEnd();
}
}

resposible código para manipulação de dados:

private List<Image> images = new ArrayList<>();

....

private void init() {
    this.imageAdapter = new ImageAdapter(this, images);
    this.gridView.setAdapter(imageAdapter);

    populateGridView();
    this.gridView.setOnScrollListener(new BasicOnScrollListener(() -> {
        populateGridView();
    }));
}

private void  populateGridView() {
    if (!isLoading) {
        isLoading = true;
        this.progressBar.setVisibility(View.VISIBLE);
        imagesRepository.getImages(currentPage, PAGE_SIZE, new IOnRepositoryDataReturn<ImagesList>() {
            @Override
            public void onData(ImagesList data) {
                clearIfNeeded();
                images.addAll(data.images);
                imageAdapter.notifyDataSetChanged();
                onFinish();
            }

            @Override
            public void onError(String error) {
                Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show();
            }

            private void clearIfNeeded() {
                if (images.size() > 1000) {
                    images.subList(0, 300).clear();
                }
            }

            private void onFinish() {
                progressBar.setVisibility(View.INVISIBLE);
                isLoading = false;
                currentPage = currentPage + 1;
            }
        });
    }
}

Tudo funciona bem, mas eu gostaria de otimizar isso. Quando já existem mais de 1000 itens do GridViewque eu gostaria de remover os primeiros 300 itens, por isso não vou correr para fora de problemas de memória.

O problema é, quando eu simplesmente remover os primeiros 300 itens de lista (como mostrado no clearIfNeeded()método na IOnRepositoryDataReturnimplementação), as mudanças de tela. Eu já não ver os itens que eu já vi antes da remoção.

Exemplo imagem. Situação se primeira linha (1-2) da imageslista é removido.

  • imagem da esquerda - grade antes de remover
  • Centro - grade após a remoção (como é, por agora, a remoção de itens na parte superior turnos de todos os itens acima)
  • direito - como eu gostaria que ele se comporte (remoção de itens em algum lugar afetar até doesnt o que é visto)

O quadrado preto está representando o GridView.

digite descrição da imagem aqui

Eu gostaria de alguma forma ajustar a posição de visualização em GridView, então eu ainda ia ver as mesmas imagens como antes da remoção.

Disposição xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/ProgressSpinner"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="@+id/GridView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/GridView" />

    <GridView
        android:id="@+id/GridView"
        android:layout_width="match_parent"
        android:layout_height="406dp"
        android:layout_marginBottom="8dp"
        android:numColumns="3"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </GridView>

Será que é mesmo possível com Grid Viewou devo procurar alguma outra possibilidade?

Shobhit Puri:

Quando já existem mais de 1000 itens na GridView Eu gostaria de remover os primeiros 300 itens, por isso não vou correr para fora de problemas de memória. Será que é mesmo possível com Grid View ou devo procurar alguma outra possibilidade?

Here is my 2 cents. If I understand correctly, your concern seems to be preventing OutOfMemory exceptions and improving memory usage and performance. If you implement the grid of photos using RecyclerView and GridLayoutManager, it would reduce many of your problems with memory. Your approach of trying to remove 300 items which are off screen, seems pretty cumbersome and error prone. Here is an excerpt from the official doc titled Create a List with RecyclerView:

RecyclerView:

The RecyclerView uses a layout manager to position the individual items on the screen and determine when to reuse item views that are no longer visible to the user. To reuse (or recycle) a view, a layout manager may ask the adapter to replace the contents of the view with a different element from the dataset. Recycling views in this manner improves performance by avoiding the creation of unnecessary views or performing expensive findViewById() lookups.

GridLayoutManager:

GridLayoutManager arranges the items in a two-dimensional grid, like the squares on a checkerboard. Using a RecyclerView with GridLayoutManager provides functionality like the older GridView layout.

You can find many tutorials for this on quick search eg: Android GridLayoutManager with RecyclerView

Acho que você gosta

Origin http://43.154.161.224:23101/article/api/json?id=138178&siteId=1
Recomendado
Clasificación