RecyclerView:动态设置item的占比,多列还是1行

在Adapter中重写该方法:onAttachedToRecyclerView

   /**
     * 网格布局,动态设置item的占比
     * 如果是2列,返回2,就是item占据1行。
     * @param recyclerView
     */
    @Override
    public void onAttachedToRecyclerView(final RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);

        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof GridLayoutManager) {
            final GridLayoutManager gridManager = ((GridLayoutManager) manager);

            gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    //注意,这里的position返回的是item在recyclerview中的位置,不是item的数据在数据列表中的位置,是把header和footer算进去的
                    int headerCount = 0;
                    if (recyclerView.getAdapter() instanceof HeaderAndFooterWrapper) {
                        headerCount = ((HeaderAndFooterWrapper) (recyclerView.getAdapter())).getHeadersCount();
                    }
                    if (position >= headerCount){
                        position = position - headerCount;
                    }
                    int type = getItemViewType(position);
                    int count =  gridManager.getSpanCount();
                    switch (type) {
                        case TYPE_COMMON_HOT:
                            return count/2;
                        case TYPE_VOICE_HOT:
                        case TYPE_COMMON_VOICE_HOT:
                        case TYPE_KSONG_HOT:
                        case TYPE_AD_HOT:
                            return count;

                        default:
                            return count/2;
                    }
                }
            });
        }
    }

你可能感兴趣的:(android)