Подтвердить что ты не робот

Большие промежутки между элементами RecyclerView при прокрутке вниз

Я делаю приложение списка ToDo, и, несмотря на его тестирование, по какой-то причине огромный разрыв возникает между элементами, когда я пытаюсь прокрутить вниз. Это всегда происходит, когда я перетаскиваю элементы, но я не вижу никаких ошибок с моим адаптером ItemTouchHelper и обратным вызовом. Было бы здорово, если бы вы могли помочь мне.

До: Before

После того, как: After

RecyclerAdapter.java

public class RecyclerAdapter extends                                                                                                                                 

RecyclerView.Adapter<RecyclerAdapter.RecyclerVH> implements ItemTouchHelperAdapter{
private LayoutInflater layoutInflater;
ArrayList<Info> data;
Context context;

public RecyclerAdapter(Context context) {
    layoutInflater = LayoutInflater.from(context);
    this.context = context;
}

public void setData(ArrayList<Info> data) {
    this.data = data;
    notifyDataSetChanged();
}

@Override
public RecyclerVH onCreateViewHolder(ViewGroup viewGroup, int position) {
    View view = layoutInflater.inflate(R.layout.custom_row, viewGroup, false);
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("R.A onClick Owen", "onClick method triggered");
        }
    });
    RecyclerVH recyclerVH = new RecyclerVH(view);
    return recyclerVH;
}

@Override
public void onBindViewHolder(RecyclerVH recyclerVH, int position) {
    Log.d("RecyclerView", "onBindVH called: " + position);

    final Info currentObject = data.get(position);
    // Current Info object retrieved for current RecyclerView item - USED FOR DELETE
    recyclerVH.listTitle.setText(currentObject.title);
    recyclerVH.listContent.setText(currentObject.content);

    /*recyclerVH.listTitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Open new Activity containing note content
            Toast.makeText(this, "Opening: " + currentObject.title, Toast.LENGTH_LONG).show();
        }
    });*/
}

public void deleteItem(int position) {
    DBInfo dbInfo = new DBInfo(context);
    dbInfo.deleteNote(data.get(position));
    // Deletes RV item/position Info object

    data.remove(position);
    // Removes Info object at specified position

    notifyItemRemoved(position);
    // Notifies the RV that item has been removed
}


@Override
public int getItemCount() {
    return data.size();
}

// This is where the Swipe and Drag-And-Drog methods come into place
@Override
public boolean onItemMove(int fromPosition, int toPosition) {
    // Swapping positions
    // ATTEMPT TO UNDERSTAND WHAT IS GOING ON HERE
    Collections.swap(data, fromPosition, toPosition);
    notifyItemMoved(fromPosition, toPosition);
    return true;
}

@Override
public void onItemDismiss(int position) {
    // Deleting item from RV and DB
    deleteItem(position);
}

class RecyclerVH extends RecyclerView.ViewHolder implements View.OnClickListener{
    // OnClickListener is implemented here
    // Can also be added at onBindViewHolder above
    TextView listTitle, listContent;

    public RecyclerVH(View itemView) {
        super(itemView);

        listTitle = (TextView) itemView.findViewById(R.id.title);
        listContent = (TextView) itemView.findViewById(R.id.content);

        listTitle.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(context, "Opening: Note" + getLayoutPosition(), Toast.LENGTH_SHORT).show();
        // PS NEVER ADD listTitle VARIABLE AS PUBLIC VARIABLE ABOVE WHICH IS GIVEN VALUE AT ONBINDVH
        // THIS IS BECAUSE THE VALUE WILL CHANGE IF ITEM IS ADDED OR DELETED
    }
}
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fab="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"
android:orientation="vertical"
android:weightSum="1">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/rounded_corners" />

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <com.melnykov.fab.FloatingActionButton
            android:id="@+id/fab_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginBottom="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginEnd="16dp"
            android:gravity="bottom|end"
            android:onClick="addNote"
            android:src="@drawable/fab_ic_add"
            fab:fab_colorNormal="@color/colorPrimary"
            fab:fab_colorPressed="@color/colorPrimaryDark"
            fab:fab_colorRipple="@color/colorPrimaryDark" />
    </RelativeLayout>
</FrameLayout>
</LinearLayout>

custom_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:id="@+id/main"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:padding="8dp"
        android:text="@string/test"
        android:textSize="18sp"
        android:textStyle="bold" />
</LinearLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/main"
    android:paddingLeft="8dp">
    <TextView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/test"
        android:textSize="15sp" />
</LinearLayout>
</RelativeLayout>

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

EDIT: Я подтвердил, что проблема не в моем классе ItemTouchHelper. (Пробовал работать без его вызова, проблема все еще возникает). Кроме того, кажется, что когда отображается диалог и клавиатура поднимается, RecyclerView в фоновом режиме сам решает проблему. После удаления диалога проблема повторяется (т.е. Прокрутка создает массивное пространство между элементами)

4b9b3361

Ответ 1

Ответ Luksprog на ответы Gabriele Mariotti.

В соответствии с doc

В версии 2.3.0 появилась новая функция API LayoutManager: автоматическое измерение! Это позволяет RecyclerView самому размеру, основанному на размере его содержимого. > Это означает, что ранее недоступные сценарии, такие как использование WRAP_CONTENT > для измерения RecyclerView, теперь возможны. Вы найдете, что все встроенные LayoutManager теперь поддерживают автоматическое измерение.

Из-за этого изменения убедитесь, что вы дважды проверяете параметры макета своих позиций: ранее проигнорированные параметры макета (например, MATCH_PARENT в направлении прокрутки) теперь будет полностью соблюден.

В макете вашего элемента вы должны изменить:

android:layout_height="match_parent"

с

android:layout_height="wrap_content" 

Ответ 2

изменение в представлении Recycler match_parent wrap_content:

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

Также измените расположение элементов xml

Сделайте высоту макета родителя match_parent wrap_content

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        />

Ответ 3

Это потому, что вы используете match_parent в высоту корневого представления элемента строки в вашем вертикально ориентированном виде listview/recyclerview. Когда вы используете это, элемент полностью расширяется к его родительскому элементу. Используйте wrap_content для высоты, когда recyclerview вертикально ориентирован и для ширины, когда она горизонтально ориентирована.

Ответ 4

У меня есть эта проблема, и я просто пользователь

android:layout_height="wrap_content"

для родительского элемента для каждого элемента.

Ответ 5

Избегайте просматривать представление в макете с контейнером следующим образом:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

<data/>

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

<TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?android:listPreferredItemHeight"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</android.support.constraint.ConstraintLayout>
</layout>

так как в этом случае match_parent выполнит свою работу, и проблема все равно останется! Скорее возьмите это так:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?android:listPreferredItemHeight"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</layout>

[Примечание: над кодом привязывается привязка к данным, не используйте теги <layout> и <data>, если не используете привязку данных]

Кроме этого, если вы должны использовать любые контейнеры групп представлений, чем просматривать атрибуты высоты и ширины в контейнере и пытаться изменить их с match_parent на wrap_content. Это должно решить проблему. Для большей прозрачности можно попробовать дать цвета фона и просмотреть его, чтобы определить актуальную проблему.