nnegier
V2EX  ›  Android

Android ItemDecoration 遇到一个奇怪的问题

  •  
  •   nnegier · Jan 7, 2024 · 10752 views
    This topic created in 898 days ago, the information mentioned may be changed or developed.

    我有一个表格布局,流式,用的 StaggeredGridLayoutManager ,我自己写了一个 SpaceItemDecoration 用于添加间距,然后刚刚问题出来了,这个间距值如果小于 7dp ,有一个内容特别长的 ItemView 就死活显示不出来,其它内容不长的 ItemView 无论怎样都正常,但如果间距大于等于 7dp 就能显示出来是正常的,所以我很困惑,为什么验证是 SpaceItemDecoration 的问题呢,因为我不添加这个 addItemDecoration 也是正常的。

    我真的不明所以,完全想不明白,那个很长的 ItemView 主要是不显示,就相当于是 Invisible 的效果,位置信息页在,按钮也能触发,也能拖动,就是不可见。好郁闷呀

    SpaceItemDecoration 的源码:

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
    
        /**
         * 列数
         */
        private int mSpanCount;
        /**
         * 间距
         */
        private int mSpace;
    
        public SpaceItemDecoration(Context context, int spanCount, float space) {
            this.mSpanCount = spanCount;
            this.mSpace = PXUtils.dp2px(context,space);
        }
    
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view);
            int spanIndex = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
            if (position == 0 || position == 1) {
                outRect.top = mSpace;
            }
            outRect.bottom = mSpace;
            if (spanIndex == 0) {
                outRect.left = mSpace;
                outRect.right = mSpace / 2;
            } else {
                outRect.left = mSpace / 2;
                outRect.right = mSpace;
            }
        }
    }
    

    使用:

            mRecyclerView = root.findViewById(R.id.recycler_view);
            mStaggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
            mRecyclerView.setLayoutManager(mStaggeredGridLayoutManager);
            mRecyclerView.addItemDecoration(new SpaceItemDecoration(getContext(), 2, 7));
    
    Supplement 1  ·  Jan 12, 2024
    不是 ItemDecoration 的问题,是我引入的一个 ShadowView 的问题,估计它里面哪里是有问题的,我得看看源码考虑重写它。
    Supplement 2  ·  Jan 12, 2024
    ShadowView 问题的根源找到了,改为:setLayerType(LAYER_TYPE_HARDWARE, null);就能解决,至于为什么我也不知道
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1645 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 16:23 · PVG 00:23 · LAX 09:23 · JFK 12:23
    ♥ Do have faith in what you're doing.