【发布时间】:2017-11-11 05:43:42
【问题描述】:
我在将 RecyclerView 放入 NestedScrollView 时遇到问题,这会导致 RecyclerView 的适配器的所有元素都被渲染。
这是一个相当大的问题,因为 RecyclerView 显示的列表可能包含数百个元素。
目前这会导致很多延迟(显然),因为它必须一次渲染所有视图,并且不能像 RecyclerView 通常那样重用任何已经膨胀的视图。
这是我当前的 XML(删除了一些膨胀以最小化它):
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:overScrollMode="never">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="90dp">
<!-- Some content -->
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- Some more content -->
</LinearLayout>
<!-- Product list -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:overScrollMode="never"/>
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
这是我在 Fragment 中的 onCreateView(),它正在膨胀包含 NestedScrollView 和 RecyclerView 的视图:
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.category_content_fragment, container, false);
ButterKnife.bind(this, root);
List<Product> products = new ArrayList<>(); //This is populated by other means, not relevant to the issue
productsRecyclerView.setNestedScrollingEnabled(false);
productsRecyclerView.setHasFixedSize(true);
productsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
ProductsContentAdapter productsContentAdapter = new ProductsContentAdapter(products);
productsRecyclerView.setAdapter(productsContentAdapter);
return root;
}
我看过这篇关于这个问题的帖子:
How to put RecyclerView inside NestedScrollView?
但遗憾的是,它并没有提到问题的最终解决方案。
澄清: RecyclerView 可以完美滚动,它会在正确的时间显示,但问题是它会立即渲染其所有子元素,这意味着可能有数百个元素,即使屏幕一次最多只显示 5-6 个。
如果需要更多信息,请随时提出问题。
------- 编辑 -------
在多次尝试其他解决方案失败后,我最终使用了 Jeeva Nandhan 的解决方案。
在问这个问题之前,我知道这是一个可能的解决方案,但我有 11 种不同的可能视图需要适合 RecyclerView,所以我希望避免它。
使用不同的 ViewTypes 后,它工作得很好。由于 ViewType 数量众多,我担心它会非常低效,但它非常光滑。
【问题讨论】:
-
尝试使用分页而不是一次膨胀所有视图
-
Ehm...为什么它适用于不同的视图类型?
标签: android xml android-recyclerview scrollview nestedscrollview