Низкая производительность прокрутки ListView с возможностью рисования - PullRequest
0 голосов
/ 29 мая 2018

Я использую специальный ArrayAdapter для заполнения ListView.

Код моего адаптера:

public class LocationAdapter extends ArrayAdapter<Location> {

    public LocationAdapter(@NonNull Context context, ArrayList<Location> locationArrayList) {
        super(context, 0, locationArrayList);
    }

    static class ViewHolder {
        public TextView nameText;
        public TextView descriptionText;
        public ImageView image;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View listItemView, @NonNull ViewGroup parent) {
        ViewHolder viewHolder;
        // check if the existing view is being reused
        if (listItemView == null) {
            // if not, inflate the view using location_list_itemlist_item.xml
            listItemView = LayoutInflater.from(getContext()).inflate(R.layout.location_list_item, parent, false);
            // configure view holder
            viewHolder = new ViewHolder();
            viewHolder.nameText = listItemView.findViewById(R.id.name_text_view);
            viewHolder.image = listItemView.findViewById(R.id.image_view);
            viewHolder.descriptionText = listItemView.findViewById(R.id.description_text_view);
            listItemView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) listItemView.getTag();
        }

        // getting Location object in this position in ArrayList
        Location currentLocation = getItem(position);

        // using ViewHolder to set text/images to views
        viewHolder.nameText.setText(currentLocation.getName());
        viewHolder.descriptionText.setText(currentLocation.getDescription());
        viewHolder.image.setImageResource(currentLocation.getImageResourceId());

        return listItemView;
    }
}

Код моего элемента списка XML, очень простой:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/name_text_view"
            android:layout_width="368dp"
            android:layout_height="22dp"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:textSize="18sp"
            android:textStyle="bold"
            android:textColor="@android:color/white"
            app:layout_constraintBottom_toBottomOf="@+id/image_view"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            tools:text="Oleviste church"
            android:elevation="2dp" />

        <ImageView
            android:id="@+id/image_view"
            android:layout_width="match_parent"
            android:layout_height="160dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:contentDescription="@string/image_content_description"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/description_text_view"
            android:layout_width="0dp"
            android:layout_height="51dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/image_view"
            tools:text="This modern museum is located inside a former seaplane hangar and boasts a submarine and an ice breaker among its exhibits." />

    </android.support.constraint.ConstraintLayout>

</LinearLayout>

Кроме того, мой XML-код ListView на всякий случай:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:overScrollMode="never"
    android:scrollingCache="false"
    android:animationCache="false"/>

Я испытываю некоторое заикание при прокрутке представления в приложении.Обратите внимание, что изображения, которые я использую, являются локальными для рисования.

До сих пор я пробовал следующее:

  1. Обрезка чертежей в Photoshop для соответствия желаемому соотношению сторон - значительно улучшение скорости, но все еще немного медленное.
  2. Использование ViewHolder - возможно незначительное улучшение скорости.
  3. Добавление атрибутов android:scrollingCache="false" и android:animationCache="false" в ListView - возможно незначительное улучшениеspeed.
  4. Использование ConstraintLayout вместо RelativeLayout - возможно, незначительное улучшение скорости.

Есть идеи, что мне следует попробовать дальше?

Ответы [ 2 ]

0 голосов
/ 02 июня 2018

Мне удалось решить проблему с помощью прокрутки ListView с использованием Glide framework .Это надежный фреймворк, нацеленный на быстрое и плавное создание списков прокрутки с любыми изображениями.

Все, что мне нужно было сделать, это изменить build.gradle:

repositories {
  mavenCentral()
}

dependencies {
  implementation 'com.github.bumptech.glide:glide:4.7.1'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
}

Затем в моем адаптереВ коде я удалил следующую строку (поскольку setImageresource больше не используется для загрузки рисованных объектов):

viewHolder.image.setImageResource(currentLocation.getImageResourceId());

И добавил следующую строку для загрузки рисованных объектов с помощью Glide:

   Glide.with(getContext()).load(currentLocation.getImageResourceId()).into(viewHolder.image);

Более подробная информацияО том, как использовать Glide, содержится в документации .

0 голосов
/ 29 мая 2018

Просто используйте RecyclerView из библиотеки поддержки вместо ListView.Это должно улучшить производительность.Обратитесь к этому такому вопросу для получения дополнительной информации. Android Recyclerview против ListView с Viewholder

...