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

Recyclerview внутри ScrollView не прокручивается плавно

Для моего приложения я использую RecyclerView внутри ScrollView, где RecyclerView имеет высоту, основанную на ее содержании, используя эту библиотеку. Прокрутка работает, но она не работает плавно, когда я просматриваю RecyclerView. Когда я просматриваю ScrollView, он прокручивается плавно.

Код, который я использую для определения RecyclerView:

LinearLayoutManager friendsLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext(), android.support.v7.widget.LinearLayoutManager.VERTICAL, false);
mFriendsListView.setLayoutManager(friendsLayoutManager);
mFriendsListView.addItemDecoration(new DividerItemDecoration(getActivity().getApplicationContext(), null));

RecyclerView в ScrollView:

<android.support.v7.widget.RecyclerView
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:id="@+id/friendsList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
4b9b3361

Ответ 1

Попробуйте сделать:

RecyclerView v = (RecyclerView) findViewById(...);
v.setNestedScrollingEnabled(false);

В качестве альтернативы вы можете изменить свой макет, используя библиотеку дизайна поддержки. Я предполагаю, что ваш текущий макет - это что-то вроде:

<ScrollView >
   <LinearLayout >

       <View > <!-- upper content -->
       <RecyclerView > <!-- with custom layoutmanager -->

   </LinearLayout >
</ScrollView >

Вы можете изменить это:

<CoordinatorLayout >

    <AppBarLayout >
        <CollapsingToolbarLayout >
             <!-- with your content, and layout_scrollFlags="scroll" -->
        </CollapsingToolbarLayout >
    </AppBarLayout >

    <RecyclerView > <!-- with standard layoutManager -->

</CoordinatorLayout >

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

Изменить (4/3/2016)

Релиз библиотек поддержки v 23.2 теперь включает функцию factory для всех стандартных LayoutManager s. Я не тестировал его, но вы, вероятно, предпочтете его использовать эту библиотеку.

<ScrollView >
   <LinearLayout >

       <View > <!-- upper content -->
       <RecyclerView > <!-- with wrap_content -->

   </LinearLayout >
</ScrollView >

Ответ 2

Мне нужно было только использовать это:

mMyRecyclerView.setNestedScrollingEnabled(false);

в моем onCreateView().

Большое спасибо!

Ответ 3

Вы можете использовать этот способ либо:

Добавьте эту строку в ваш XML файл recyclerView:

android:nestedScrollingEnabled="false"

Или в коде Java:

RecyclerView.setNestedScrollingEnabled(false);

Надеюсь, это помогло.

Ответ 4

Вы можете попробовать как с помощью XML, так и программно. Но проблема, с которой вы можете столкнуться (ниже API 21), делая это с XML, не будет работать. Поэтому лучше настроить его программно в своей деятельности/фрагменте.

Код XML:

<android.support.v7.widget.RecyclerView
      android:id="@+id/recycleView"
      android:layout_width="match_parent"
      android:visibility="gone"
      android:nestedScrollingEnabled="false"
      android:layout_height="wrap_content"
      android:layout_below="@+id/linearLayoutBottomText" /> 

Программный:

 recycleView = (RecyclerView) findViewById(R.id.recycleView);
 recycleView.setNestedScrollingEnabled(false);

Ответ 5

У меня были подобные проблемы (я попытался создать вложенный RecyclerViews, похожий на дизайн Google PlayStore). Лучший способ справиться с этим - это подклассификация дочерних RecyclerViews и переопределение методов onInterceptTouchEvent и onTouchEvent. Таким образом, вы получаете полный контроль над тем, как эти события ведут себя и в конечном итоге прокручиваются.

Ответ 6

Использование Nested Scroll View вместо Scroll View решило мою проблему

<LinearLayout> <!--Main Layout -->
   <android.support.v4.widget.NestedScrollView>
     <LinearLayout > <!--Nested Scoll View enclosing Layout -->'

       <View > <!-- upper content --> 
       <RecyclerView >


     </LinearLayout > 
   </android.support.v4.widget.NestedScrollView>
</LinearLayout>

Ответ 7

Краткое изложение всех ответов (преимущества и недостатки)

Для одного рециркулятора

Вы можете использовать его в макете координатора.

Преимущество - он не будет загружать целые пункты просмотра переработчика. Так плавная загрузка.

Недостаток - вы не можете загрузить два окна просмотра в макете координатора - это вызывает проблемы с прокруткой

ссылка - fooobar.com/questions/57909/...

Для нескольких recylerview с минимальным количеством строк

вы можете загрузить внутри NestedScrollView

Преимущество - оно будет плавно прокручиваться

Недостаток - он загружает все ряды повторного просмотра, поэтому ваша деятельность открывается с задержкой

ссылка - fooobar.com/questions/57909/...

Для нескольких recylerview с большими строками (более 100)

Вы должны пойти с переработчиком.

Преимущество - плавная прокрутка, плавная загрузка

Недостаток - вам нужно написать больше кода и логики

Загрузите каждый recylerview внутри основного переработчика просмотра с помощью нескольких владельцев

например:

MainRecyclerview

-ChildRecyclerview1 (ViewHolder1)

-ChildRecyclerview2 (ViewHolder2)

-ChildRecyclerview3 (ViewHolder3) 

-Any other layout   (ViewHolder4)

Ссылка для multi-viewHolder - fooobar.com/questions/12061/...

Ответ 8

<ScrollView >
   <LinearLayout >

       <View > <!-- upper content -->
       <RecyclerView > <!-- with wrap_content -->

   </LinearLayout >
</ScrollView >

Ответ 9

Если вы используете VideoView или виджеты с большим весом в своих дочерних представлениях, оставьте RecyclerView с высотой wrap_content внутри NestedScrollView с высотой match_parent Тогда прокрутка будет работать гладко так, как вам хочется.

FYI,

<android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:nestedScrollingEnabled="false"
            android:layout_height="wrap_content"
            android:clipToPadding="false" />

</android.support.v4.widget.NestedScrollView>

Спасибо Микро, это было от твоего намека!

Картик

Ответ 10

XML-код:

<android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v7.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clipToPadding="false" />

        </android.support.v4.widget.NestedScrollView>

в коде Java:

  recycleView = (RecyclerView) findViewById(R.id.recycleView);
     recycleView.setNestedScrollingEnabled(false);

Ответ 11

Или вы можете просто установить android:focusableInTouchMode="true" в своем представлении переработчика

Ответ 12

<?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">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent">

            <android.support.constraint.ConstraintLayout
                android:id="@+id/constraintlayout_main"
                android:layout_width="match_parent"
                android:layout_height="@dimen/layout_width_height_fortyfive"
                android:layout_marginLeft="@dimen/padding_margin_sixteen"
                android:layout_marginRight="@dimen/padding_margin_sixteen"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent">

                <TextView
                    android:id="@+id/textview_settings"
                    style="@style/textviewHeaderMain"
                    android:gravity="start"
                    android:text="@string/app_name"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintRight_toRightOf="parent" />

            </android.support.constraint.ConstraintLayout>

            <android.support.constraint.ConstraintLayout
                android:id="@+id/constraintlayout_recyclerview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/padding_margin_zero"
                android:layout_marginTop="@dimen/padding_margin_zero"
                android:layout_marginEnd="@dimen/padding_margin_zero"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/constraintlayout_main">

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/recyclerview_list"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:nestedScrollingEnabled="false"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintRight_toRightOf="parent" />

            </android.support.constraint.ConstraintLayout>

        </android.support.constraint.ConstraintLayout>

    </android.support.v4.widget.NestedScrollView>

</android.support.constraint.ConstraintLayout>

Этот код работает для в ConstraintLayout Android

Ответ 13

Замена ScrollView на NestedScrollView привела к плавной прокрутке вниз.