RecyclerView嵌套ViewPager下的Wrap_Content问题


最近在开发商城,主页面这样:
页面效果
三层嵌套:rv+vp+gv,期间发现了不少问题,梳理如下:

一、gridView嵌套问题
(1)rv嵌套gv中,只显示一行

无论设置match_parent 还是 wrap_content,都只显示一行。解决方案:使用最大模式测量(最大父控件高度)

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
(2)grdivew 自动获取焦点,滑动vp时,导致rv自动竖直滚动

解决:rv设置 descendantFocusability属性。

blocksDescendants:viewgroup会覆盖子类控件而直接获得焦点
二、ViewPager高度不固定问题
(1)ViewPager高度依赖于 子Fragmment高度,动态测量。
public class AutoHeightViewPager extends ViewPager {

    private int current;
    private int height = 0;

    /**
     * 保存position与对于的View
     */
    private HashMap<Integer, View> childrenViews = new LinkedHashMap();

    public AutoHeightViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        if (childrenViews.size() > current) {
            View child = childrenViews.get(current);
            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            height = child.getMeasuredHeight();
        }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    //切换tab的时候重新设置viewpager的高度
    public void resetHeight(int current) {
        this.current = current;
        if (childrenViews.size() > current) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();
            if (layoutParams == null) {
                layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
            } else {
                layoutParams.height = height;
            }
            setLayoutParams(layoutParams);
        }
    }

    /**
     * 保存position与对应的View
     */
    public void setObjectForPosition(View view, int position) {
        childrenViews.put(position, view);
    }
(2)android 9.0上vp第一页数据初始不展示(高度测量失败)。

解决方案:在Fragment渲染完成,或rv渲染完成后,手动调用测量,重新绘制一遍。

  Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                if (tabPosition == 0) {
                    viewPager.resetHeight(0);
                }
                return false;
            }
        });

源码地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章