Как использовать RecyclerView внутри NestedScrollView?
Как пользоваться RecyclerView
внутри NestedScrollView
?RecyclerView
содержимое не видно после настройки адаптера.
ОБНОВЛЕНИЕ Код макета обновлен.
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/keyline_1">
</RelativeLayout>
<View
android:id="@+id/separator"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#e5e5e5" />
<android.support.v7.widget.RecyclerView
android:id="@+id/conversation"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
27 ответов
Замените свой recyclerView на,
<android.support.v7.widget.RecyclerView
android:id="@+id/conversation"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Вот,
app:layout_behavior="@string/appbar_scrolling_view_behavior"
будет управлять остальными вещами.
Еще одна вещь, нет необходимости помещать свой RecyclerView внутри NestedScrollView
1) Вы должны использовать библиотеку поддержки 23.2.0 (или) выше
2) и RecyclerView
высота будет wrap_content
,
3) recyclerView.setNestedScrollingEnabled(false)
Но при этом шаблон утилизации не работает. (т.е. все виды будут загружены одновременно, потому что wrap_content
нужна высота завершения RecyclerView
так будет рисовать всех детей View
с сразу. Нет вид будет переработан). Старайтесь не использовать этот шаблон утилитой, если это действительно не требуется. Попробуй использовать viewType
и добавьте все другие представления, которые нужно прокрутить до RecyclerView
вместо того, чтобы использовать RecyclerView
в Scrollview
, Влияние на производительность будет очень высоким.
Чтобы сделать это просто "он просто действует как LinearLayout
со всеми детскими взглядами
ОБНОВЛЕНИЕ 1
Начиная с библиотеки поддержки Android 23.2.0 был добавлен метод setAutoMeasureEnabled(true)
для LayoutManagers. Это делает RecyclerView, чтобы обернуть его содержимое и работает как шарм.
http://android-developers.blogspot.ru/2016/02/android-support-library-232.html
Так что просто добавьте что-то вроде этого:
LayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setAutoMeasureEnabled(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setNestedScrollingEnabled(false);
ОБНОВЛЕНИЕ 2
С 27.1.0 setAutoMeasureEnabled
устарела, поэтому вы должны предоставить пользовательскую реализацию LayoutManager с переопределенным методом isAutoMeasureEnabled()
Но после многих случаев использования RecyclerView я настоятельно рекомендую не использовать его в режиме обтекания, потому что это не то, для чего он предназначен. Попробуйте провести рефакторинг всего макета, используя обычный RecyclerView с несколькими типами элементов. Или используйте подход с LinearLayout, который я описал ниже как последнее средство
Старый ответ (не рекомендуется)
Ты можешь использовать RecyclerView
внутри NestedScrollView
, Прежде всего, вы должны реализовать свой собственный LinearLayoutManager
, это делает ваш RecyclerView
обернуть его содержание. Например:
public class WrappingLinearLayoutManager extends LinearLayoutManager
{
public WrappingLinearLayoutManager(Context context) {
super(context);
}
private int[] mMeasuredDimension = new int[2];
@Override
public boolean canScrollVertically() {
return false;
}
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
if (getOrientation() == HORIZONTAL) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
heightSpec,
mMeasuredDimension);
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
measureScrapChild(recycler, i,
widthSpec,
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view.getVisibility() == View.GONE) {
measuredDimension[0] = 0;
measuredDimension[1] = 0;
return;
}
// For adding Item Decor Insets to view
super.measureChildWithMargins(view, 0, 0);
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(
widthSpec,
getPaddingLeft() + getPaddingRight() + getDecoratedLeft(view) + getDecoratedRight(view),
p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(
heightSpec,
getPaddingTop() + getPaddingBottom() + getDecoratedTop(view) + getDecoratedBottom(view),
p.height);
view.measure(childWidthSpec, childHeightSpec);
// Get decorated measurements
measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
После этого используйте это LayoutManager
для тебя RecyclerView
recyclerView.setLayoutManager(new WrappingLinearLayoutManager(getContext()));
Но вы также должны вызвать эти два метода:
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(false);
Вот setNestedScrollingEnabled(false)
отключить прокрутку для RecyclerView
, поэтому он не перехватывает событие прокрутки от NestedScrollView
, А также setHasFixedSize(false)
определить, что изменения в содержимом адаптера могут изменить размер RecyclerView
Важное примечание: в некоторых случаях это решение немного глючит и имеет проблемы с производительностью, поэтому, если у вас есть много элементов в вашем RecyclerView
Я бы порекомендовал использовать пользовательские LinearLayout
на основе реализации представления списка, создайте для него аналог адаптера и сделайте так, чтобы он вел себя как ListView
или же RecyclerView
Ты можешь использовать android:fillViewport="true"
делать NestedScrollView
измерить RecyclerView
, RecyclerView
will fill the remaining height. so if you want to scroll the NestScrollView
Вы можете установить RecyclerView
"s minHeight
,
Просто добавив recyclerView.setNestedScrollingEnabled(false);
до setAdapter
сам работал на меня. Я не добавил app:layout_behavior="@string/appbar_scrolling_view_behavior"
в любом месте и не установил никакого собственного менеджера макета
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/white"
android:text="Some Text..."
android:padding="15dp" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:padding="15dp"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Quick Links"
android:textColor="@color/black"
android:textStyle="bold"
android:textAllCaps="true"
android:paddingLeft="20dp"
android:drawableLeft="@drawable/ic_trending_up_black_24dp"
android:drawablePadding="10dp"
android:layout_marginBottom="10dp"
android:textSize="16sp"/>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#efefef"/>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
Это то, что работает для меня
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.v4.widget.NestedScrollView>
За androidx
это называется androidx.core.widget.NestedScrollView
- и это также прокручивает как масло со свойствами isScrollContainer
а также measureAllChildren
включено:
<!-- Scrolling Content -->
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:isScrollContainer="true"
android:measureAllChildren="true"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fastScrollEnabled="true"
android:scrollbarStyle="insideInset"
android:scrollbars="vertical"
android:splitMotionEvents="false"
android:verticalScrollbarPosition="right"/>
</androidx.core.widget.NestedScrollView>
Существует простой и тестовый код, который вы можете проверить
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.NestedScrollView>
Я использовал RecyclerView внутри NestedScrollView, и он работал для меня. Единственное, о чем я должен был помнить, это то, что NestedScrollView принимает только одно дочернее представление. Так что в моем случае я использовал видовую группу LienearLayout, в которой находился мой RecyclerView, а также ряд других представлений, которые мне были нужны.
Я испытываю одну проблему, помещающую мой RecyclerView в NestedScrollView. Я понял, что прокрутка содержимого моего RecyclerView замедлилась.
Позже я понял, что мой RecyclerView получает событие прокрутки и, следовательно, конфликтует с режимом прокрутки NestedScrollView.
Таким образом, чтобы решить эту проблему, я должен был отключить функцию прокрутки моего RecyclerView с помощью этого метода movieListNewRecyclerView.setNestedScrollingEnabled(false);
Вы можете проверить мой Instagram для короткого видео о том, что я на самом деле сделал. Это моя ручка instagram ofelix03
Попробуйте использовать эту библиотеку - https://github.com/serso/android-linear-layout-manager.
LayoutManager из библиотеки заставляет RecyclerView обернуть его содержимое. В этом случае RecyclerView будет "таким же большим, как внутренние виды", поэтому у него не будет полос прокрутки, и пользователь будет использовать возможности прокрутки NestedScrollView. Следовательно, он не будет неоднозначным, как "прокручиваемый внутри прокручиваемый".
Вот код, который я использую, чтобы избежать проблем с прокруткой:
mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mRecyclerView.getLayoutManager().setAutoMeasureEnabled(true);
mRecyclerView.setNestedScrollingEnabled(false);
mRecyclerView.setHasFixedSize(false);
У меня есть Viewpager и RecyclerView внутри NestedScrollView. После добавления строк ниже
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(false);
Я решил проблему медленной прокрутки и задержки прокрутки.
Если вы хотите использовать RecyclerView в NestedScrollView, это просто сложно, просто установите:
RecyclerView
recyclerView.setHasFixedSize(ложь) (java / kt)
android:nestedScrollingEnabled= "ложь"
android:layout_height= "wrap_content"
android: overScrollMode = "никогда"
NestedScrollView
- android: fillViewport = "правда"
это работа для меня, и вы также можете использовать много RecyclerView в NestedScrollView с этим.
Если вы используете RecyclerView ScrollListener внутри NestedScrollView, слушатель addOnScrollListener не работает должным образом, если вы используете оба.
Используйте этот код.
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
......
}
});
этот код работает нормально RecyclerView ScrollListener внутри NestedScrollView.
Спасибо
Есть много хороших ответов. Ключ в том, что вы должны установить nestedScrollingEnabled
в false
, Как уже упоминалось выше, вы можете сделать это в коде Java:
mRecyclerView.setNestedScrollingEnabled(false);
Но также у вас есть возможность установить такое же свойство в коде xml (android:nestedScrollingEnabled="false"
):
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:nestedScrollingEnabled="false"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Вы не можете использовать представление рециркулятора во вложенном представлении прокрутки. Он не предназначен для того, чтобы содержать дополнительные прокручиваемые представления, но потому, что он является дочерним по отношению к самому макету с прокруткой, вам нужен вложенный прокручиваемый вид. У меня возникла та же проблема, но в итоге я переместил свое текстовое представление в представление заголовка в представлении реселлера, сделало его рекурсором прямым потомком макета координатора и удалило вложенное представление прокрутки. Тогда все мои проблемы исчезли.
Если вы используете RecyclerView-23.2.1
или позже. Следующее решение будет работать нормально:
В свой макет добавить RecyclerView, как это:
<android.support.v7.widget.RecyclerView
android:id="@+id/review_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
И в вашем файле Java:
RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager=new LinearLayoutManager(getContext());
layoutManager.setAutoMeasureEnabled(true);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(new YourListAdapter(getContext()));
Вот layoutManager.setAutoMeasureEnabled(true);
сделает свое дело.
Проверьте эту проблему и этот блог разработчика для получения дополнительной информации.
Вы можете использовать мой пример кода
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<LinearLayout
android:id="@+id/fl_all_brand"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".view.fragment.AllBrandFragment">
<androidx.core.widget.NestedScrollView
android:id="@+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:id="@+id/fl_all_brand1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!--<include layout="@layout/content_home" />-->
<TextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="@dimen/_15sdp"
android:layout_marginTop="@dimen/_20sdp"
android:fontFamily="@font/lexend_semibold"
android:text="@string/DISPLAY_LIGHTS"
android:textColor="@color/gray_scale_placehold"
android:textSize="@dimen/_16ssp" />
<LinearLayout
android:id="@+id/recyclerLayout"
android:layout_width="match_parent"
android:layout_height="@dimen/_280sdp">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerviewobj"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="@dimen/_10sdp"
android:layout_marginTop="@dimen/_20sdp"
android:layout_marginEnd="@dimen/_10sdp"
android:orientation="horizontal"
android:nestedScrollingEnabled="false"
android:layout_marginBottom="@dimen/_20sdp"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
/>
</LinearLayout>
<TextView
android:id="@+id/notfound"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="@dimen/_15sdp"
android:layout_marginTop="@dimen/_20sdp"
android:layout_marginBottom="@dimen/_20sdp"
android:fontFamily="@font/lexend_semibold"
android:text="@string/DISPLAY_LIGHTS"
android:gravity="center"
android:visibility="gone"
android:textColor="?attr/hintTextColors"
android:textSize="@dimen/_12ssp" />
<TextView
android:id="@+id/recommendTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/addDeviceLayout"
android:layout_below="@+id/recyclerviewobj"
android:layout_marginStart="@dimen/_16sdp"
android:layout_marginTop="@dimen/_7sdp"
android:fontFamily="@font/lexend_semibold"
android:text="@string/RECOMMENDATION"
android:textColor="@color/gray_scale_placehold"
android:textSize="@dimen/_16ssp" />
<LinearLayout
android:id="@+id/addDeviceLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/createRoomLayout"
android:layout_marginTop="@dimen/_14sdp"
android:background="?attr/buttonTextColor"
android:orientation="vertical"
tools:visibility="visible">
<ImageView
android:id="@+id/addBtn"
android:layout_width="@dimen/_28sdp"
android:layout_height="@dimen/_28sdp"
android:layout_marginStart="@dimen/_16sdp"
android:layout_marginTop="@dimen/_8sdp"
android:src="@drawable/ic_thermostates_icon"
app:tint="?attr/colorPrimaryDark" />
<TextView
android:id="@+id/addDevice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/_16sdp"
android:layout_marginTop="@dimen/_5sdp"
android:fontFamily="@font/lexend_bold"
android:text="@string/PROGRAM_DISPLAY_SENSOR_PLUGS"
android:textColor="?attr/colorPrimaryDark"
android:textSize="@dimen/_12ssp" />
<TextView
android:id="@+id/summry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/_16sdp"
android:layout_marginTop="@dimen/_8sdp"
android:layout_marginBottom="@dimen/_6sdp"
android:fontFamily="@font/lexend_medium"
android:text="@string/DISPLAY_SENSOR_SUB_TITLE"
android:textColor="?attr/secondaryTextColor"
android:textSize="@dimen/_9ssp" />
<RelativeLayout
android:id="@+id/container3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/_6sdp"
android:layout_marginTop="@dimen/_6sdp"
android:layout_marginBottom="@dimen/_10sdp">
<TextView
android:id="@+id/get_started"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginStart="@dimen/_10sdp"
android:fontFamily="@font/lexend_semibold"
android:text="@string/RECOMMENDED_GROUP"
android:textAllCaps="true"
android:textSize="@dimen/_9ssp" />
<ImageView
android:id="@+id/forward_arrow"
android:layout_width="@dimen/_16sdp"
android:layout_height="@dimen/_16sdp"
android:layout_alignParentEnd="true"
android:layout_marginRight="@dimen/_20sdp"
android:src="@drawable/ic_forward_arrow"
app:tint="?attr/colorPrimary" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/createRoomLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginTop="@dimen/_9sdp"
android:layout_marginBottom="@dimen/_20sdp"
android:background="?attr/buttonTextColor"
android:orientation="vertical"
tools:visibility="visible">
<ImageView
android:id="@+id/addBtnRoom"
android:layout_width="@dimen/_28sdp"
android:layout_height="@dimen/_28sdp"
android:layout_marginStart="@dimen/_16sdp"
android:layout_marginTop="@dimen/_8sdp"
android:src="@drawable/rgb_light_new"
app:tint="?attr/colorPrimaryDark" />
<TextView
android:id="@+id/addRooms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/_16sdp"
android:layout_marginTop="@dimen/_5sdp"
android:fontFamily="@font/lexend_bold"
android:text="@string/DISPLAY_RGBW"
android:textColor="?attr/colorPrimaryDark"
android:textSize="@dimen/_12ssp" />
<TextView
android:id="@+id/summry1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/_16sdp"
android:layout_marginTop="@dimen/_8sdp"
android:layout_marginBottom="@dimen/_6sdp"
android:fontFamily="@font/lexend_medium"
android:text="@string/PROGRAM_DISPLAY_RGB_MSG"
android:textColor="?attr/secondaryTextColor"
android:textSize="@dimen/_9ssp" />
<RelativeLayout
android:id="@+id/container99"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/_6sdp"
android:layout_marginTop="@dimen/_6sdp"
android:layout_marginBottom="@dimen/_10sdp">
<TextView
android:id="@+id/get_started_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginStart="@dimen/_10sdp"
android:fontFamily="@font/lexend_semibold"
android:text="@string/RECOMMENDED_GROUP"
android:textAllCaps="true"
android:textSize="@dimen/_9ssp" />
<ImageView
android:id="@+id/forward_arrow1"
android:layout_width="@dimen/_16sdp"
android:layout_height="@dimen/_16sdp"
android:layout_alignParentEnd="true"
android:layout_marginRight="@dimen/_20sdp"
android:src="@drawable/ic_forward_arrow"
app:tint="?attr/colorPrimary" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</LinearLayout>
</layout>
здесь используйте это свойство recyclerview
app:layout_behavior="@string/appbar_scrolling_view_behavior"
и отключил вложенную прокрутку recyclerview, как это
android:nestedScrollingEnabled="false"
Одним из решений, позволяющих сохранить функцию рециркуляции в обзоре утилизатора и избежать его повторной загрузки для загрузки всех ваших данных, является установка фиксированной высоты в самом обзоре утилизатора. Делая это, просмотр переработчика ограничивается только загрузкой настолько, насколько его высота может показать пользователю, таким образом, перерабатывая его элемент, если вы когда-либо прокрутите его вниз / вверх.
nestedScrollView.setNestedScrollingEnabled(true);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
//...
}
});
<androidx.core.widget.NestedScrollView
android:id="@+id/nested"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:layout_below="@id/appBarLayout_orders"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<androidx.constraintlayout.widget.ConstraintLayout ...
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
Не используйте recyclerView внутри NestedScrollView. это может вызвать каскадные проблемы! Я предлагаю использовать ItemViewTypes в RecyclerView для обработки нескольких видов представлений. просто добавьте RecyclerView с шириной и высотой match_parent. затем в вашем recyclerViewAdapter переопределите getItemViewType и используйте позицию для обработки того, какой макет нужно надуть. после этого вы можете обрабатывать свой видовой держатель с помощью метода onBindViewHolder.
В моем случае это то, что у меня работает
Положить
android:fillViewport="true"
внутри NestedScrollView.Сделайте высоту RecyclerView равной wrap_content, т.е.
android:layout_height="wrap_content"
Добавьте это в RecyclerView
android:nestedScrollingEnabled="false"
ИЛИ ЖЕ
Программно в вашем классе Kotlin
recyclerView.isNestedScrollingEnabled = false
mRecyclerView.setHasFixedSize(false)
Мне пришлось реализовать CoordinatorLayout с прокруткой на панели инструментов, и мне просто пришлось целый день возиться с этим. У меня это работает, удалив NestedScrollView на всех. Так что я просто использую RelativeLayout в корне.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_nearby"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</RelativeLayout>
Я использовал это замечательное расширение (написано на kotlin, но может также использоваться на Java)
https://github.com/Widgetlabs/expedition-nestedscrollview
В основном вы получаете NestedRecyclerView
внутри любого пакета скажем, утилит в вашем проекте, а затем просто создайте свой recyclerview, например
<com.your_package.utils.NestedRecyclerView
android:id="@+id/rv_test"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Проверьте эту замечательную статью Марка Кнаупа
В моем случае дочерним элементом NestedScrollview является ConstraintLayout. Он не работает должным образом, я заменил его на LinearLayout. Может кому поможет.
<androidx.core.widget.NestedScrollView
android:id="@+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false"
app:layout_constraintBottom_toTopOf="@+id/divider"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tinTitle"/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
По крайней мере, еще в том, что касается компонентов материала 1.3.0-alpha03, не имеет значения, является ли RecyclerView вложенным (не в ScrollView или NestedScrollView). Просто положи
app:layout_behavior="@string/appbar_scrolling_view_behavior"
на своем родительском элементе верхнего уровня, который является родственником AppBarLayout в CoordinatorLayout.
Это сработало для меня при использовании единой архитектуры Activity с Jetpack Naviagation, где все фрагменты используют один и тот же AppBar из макета Activity. Я делаю FragmentContainer прямым потомком CoordinatorLayout, который также содержит AppBarLayout, как показано ниже. RecyclerViews в различных фрагментах прокручиваются нормально, а панель приложений сворачивается и появляется снова, как ожидалось.
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="@+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
app:defaultNavHost="true"
app:navGraph="@navigation/mobile_navigation"/>
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:liftOnScroll="true">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_scrollFlags="scroll|enterAlways|snap" />
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
liftOnScroll
(используется для того, чтобы панели приложений выглядели так, как будто они имеют нулевую высоту в верхней части страницы) работает, если каждый фрагмент передает идентификатор своего RecyclerView в
AppBarLayout.liftOnScrollTargetViewId
в
Fragment.onResume
. Или передайте 0, если фрагмент не прокручивается.
RecyclerView с NestedScrollView
<android.support.v7.widget.RecyclerView
android:id="@+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />