Я столкнулся с проблемой производительности при добавлении нескольких RecyclerView внутри NestedScrollView. Я показываю два горизонтальных сверху и вертикального RecyclerView внизу.
Я добавил строку ниже
recyclerView.setNestedScrollingEnabled(false);
Это показывает весь список должным образом, но реальный вопрос - я столкнулся с проблемой производительности.
Все три RecyclerView отображаются через ~ 5 секунд всех ответов. Это также блокирует пользовательский интерфейс, поскольку он занят для RecyclerView.
XML
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/llTabs"
android:fillViewport="true"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.turacomobile.gb.utils.CustomSFUIMediumTextView
android:id="@+id/tvMyBrands"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="My Streamz (Brands)"
android:textColor="@color/black" />
<android.support.v7.widget.RecyclerView
android:id="@+id/rvMyBrands"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="@dimen/dimen_5dp"
android:paddingRight="@dimen/dimen_5dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<com.turacomobile.gb.utils.CustomSFUIMediumTextView
android:id="@+id/tvRecommendedBrands"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Recommended Streamz (Brands)"
android:textAppearance="@style/TabLayoutTextStyleSearch"
android:textColor="@color/black" />
<android.support.v7.widget.RecyclerView
android:id="@+id/rvRecommendedBrands"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="@dimen/dimen_5dp"
android:paddingRight="@dimen/dimen_5dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<com.turacomobile.gb.utils.CustomSFUIMediumTextView
android:id="@+id/tvSearchMyStreamz"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Food from My Streamz Brands"
android:textColor="@color/black" />
<android.support.v7.widget.RecyclerView
android:id="@+id/my_recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
JAVA
rvSearchStreamz = findViewById(R.id.my_recycler_view);
rvMyBrands = findViewById(R.id.rvMyBrands);
rvRecommendedBrands = findViewById(R.id.rvRecommendedBrands);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
rvSearchStreamz.setLayoutManager(llm);
rvSearchStreamz.setNestedScrollingEnabled(false);
rvSearchStreamz.setHasFixedSize(false);
LinearLayoutManager llmMy = new LinearLayoutManager(this);
llmMy.setOrientation(LinearLayoutManager.HORIZONTAL);
rvMyBrands.setLayoutManager(llmMy);
rvMyBrands.setNestedScrollingEnabled(false);
rvMyBrands.setHasFixedSize(false);
LinearLayoutManager llmRecommended = new LinearLayoutManager(this);
llmRecommended.setOrientation(LinearLayoutManager.HORIZONTAL);
rvRecommendedBrands.setLayoutManager(llmRecommended);
rvRecommendedBrands.setNestedScrollingEnabled(false);
rvRecommendedBrands.setHasFixedSize(false);
Проблема заключается в NestedScrollView. Вы не должны использовать RecyclerView внутри NestedScrollView, потому что RecyclerView не перерабатывает ничего в NestedScrollView (вы можете протестировать его с записью записи в onCreateView и onBindView). Измените тип макета контейнера, например LinearLayout, RelativeLayout и т.д.
При первом изменении Адаптер инициализируется
HorizontalAdapterOne hAdapterOne;
HorizontalAdapterTwo hAdapterTwo;
И напишите это в свой метод onCreate в Activity
hAdapterOne=new HorizontalAdapterOne(context,new ArrayList<DemoItemOne>);
hAdaptertwo=new HorizontalAdapterTwo(context,new ArrayList<DemoItemTwo>);
Добавьте метод в адаптер
public void refreshList(ArrayList<DemoModel> demoList){
if(demoList!=null && demoList.size()>0){
this.demoActualList.addAll(demoList);
notifyDataSetChanged();
}
}
После получения данных из API затем вызовите этот метод из своей активности
hAdapterOne.refreshList(demoListFromAPI)
Или вы можете использовать представление пользовательского списка вместо представления Recycler для вертикальной распечатки. Проверьте приведенный ниже список Класс класса
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ListView;
public class ExpandableHeightListView extends ListView {
boolean expanded = true;
public ExpandableHeightListView(Context context) {
super(context);
}
public ExpandableHeightListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExpandableHeightListView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public boolean isExpanded() {
return expanded;
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// HACK! TAKE THAT ANDROID!
if (isExpanded()) {
// Calculate entire height by providing a very large height hint.
// View.MEASURED_SIZE_MASK represents the largest height possible.
int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
}
Я бы порекомендовал вам пойти с разбивкой на страницы. Что касается производительности, то это может быть лучшим катализатором.
В разбивке на страницы мы загружаем и устанавливаем только определенное количество контента в recyclerview.
Блокирование потока пользовательского интерфейса и резкое сокращение также, пожалуйста, перейдите с асинхронной задачей, если у вас есть много данных для визуализации в качестве UI. Therad должен поддерживаться как можно легче.
Ниже приведена ссылка, в которой вы можете получить представление о реализации. https://medium.com/@etiennelawlor/pagination-with-recyclerview-1cb7e66a502b
recyclerView