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

前言:使用NestedScrollView嵌套RecyclerView。

解决步骤一:固定高度

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

     binding.nestedScrollV.post(new Runnable() {
        @Override
        public void run() {
            binding.selectList.getLayoutParams().height = binding.nestedScrollV.getHeight(); // 使用NestedScrollView的高度
            binding.productList.getLayoutParams().height = binding.nestedScrollV.getHeight();                        
            binding.selectList.setLayoutParams(binding.selectList.getLayoutParams());  
            binding.productList.setLayoutParams(binding.productList.getLayoutParams());
     });

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

public class MNestedScrollViewBox extends NestedScrollView {

    public MNestedScrollViewBox(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    // 使用NestedScrollView嵌套RecyclerView,会导致RecyclerView复用机制失效,RecyclerView会将所有数据一次性全部加载。
    // 解决方法:重写measureChildWithMargins,让NestedScrollView测量RecyclerView时 不使用MeasureSpec.UNSPECIFIED模式即可。
    @Override
    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
        child.measure(parentWidthMeasureSpec, parentHeightMeasureSpec);
    }

}

使用:




    

        

        

    

你可能感兴趣的:(Android,android)