• RecyclerView嵌套布局,导致RecyclerView复用失效 解决


    前言:使用NestedScrollView嵌套RecyclerView。

    解决步骤一:固定高度

    NestedScrollView嵌套RecyclerView时,RecyclerView的高度是无限大,所以要将RecyclerView设置固定高度。在代码中固定的,灵活度更高。

    1.      binding.nestedScrollV.post(new Runnable() {
    2.         @Override
    3.         public void run() {
    4. binding.selectList.getLayoutParams().height = binding.nestedScrollV.getHeight(); // 使用NestedScrollView的高度
    5. binding.productList.getLayoutParams().height = binding.nestedScrollV.getHeight();
    6. binding.selectList.setLayoutParams(binding.selectList.getLayoutParams());
    7. binding.productList.setLayoutParams(binding.productList.getLayoutParams());
    8.      });

    解决步骤二:重写NestedScrollView的 measureChildWithMargins() 函数

    1. public class MNestedScrollViewBox extends NestedScrollView {
    2. public MNestedScrollViewBox(@NonNull Context context, @Nullable AttributeSet attrs) {
    3. super(context, attrs);
    4. }
    5. // 使用NestedScrollView嵌套RecyclerView,会导致RecyclerView复用机制失效,RecyclerView会将所有数据一次性全部加载。
    6. // 解决方法:重写measureChildWithMargins,让NestedScrollView测量RecyclerView时 不使用MeasureSpec.UNSPECIFIED模式即可。
    7. @Override
    8. protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
    9. child.measure(parentWidthMeasureSpec, parentHeightMeasureSpec);
    10. }
    11. }

    使用:

    1. "1.0" encoding="utf-8"?>
    2. "http://schemas.android.com/apk/res/android"
    3. xmlns:tools="http://schemas.android.com/tools"
    4. android:layout_width="match_parent"
    5. android:layout_height="match_parent"
    6. android:background="@color/color_F5F6F7"
    7. android:fillViewport="true"
    8. android:overScrollMode="never"
    9. tools:context=".ui.fragment.shopdetail.OrderFoodFragment">
    10. android:layout_width="match_parent"
    11. android:layout_height="match_parent">
    12. android:id="@+id/select_list"
    13. android:layout_width="84dp"
    14. android:layout_height="match_parent"
    15. android:overScrollMode="never"
    16. tools:listitem="@layout/widget_select_item_ho" />
    17. android:id="@+id/product_list"
    18. android:layout_width="0dp"
    19. android:layout_height="match_parent"
    20. android:layout_weight="1"
    21. android:background="@color/white"
    22. android:overScrollMode="never"
    23. android:paddingStart="8dp"
    24. tools:ignore="RtlSymmetry"
    25. tools:listitem="@layout/widget_product_item_ho" />

  • 相关阅读:
    C语言之初阶指针
    Python入门到精通
    【Rust 日报】2022-11-06 二维码生成工具
    从装饰模式和职责链模式看链式结构模式
    简单工厂模式
    Starknet架构之Starknet state、State commitment
    leetcode-电话号码组合(C CODE)
    splay平衡树
    【python】这么**得小姐姐网~不敢赶紧采集一波~免得它没了
    整合定位技术应对物联网碎片化场景应用
  • 原文地址:https://blog.csdn.net/Lan_Se_Tian_Ma/article/details/134510946