基于RecyclerView的瀑布流实现

fragment的布局:





        


item的布局



    
        
        

    
    
        


            
            
        
    




fragment中对RecyclerView的初始化:

View view  =inflater.inflate(R.layout.fragment_vod_list, container, false);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.id_recyclerview);
        mspan_count=2;
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(mspan_count,StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        mRecyclerView.setLayoutManager(layoutManager);
        mVodAdapter = new VodAdapter();
        mRecyclerView.setAdapter(mVodAdapter);
        SpacesItemDecoration decoration=new SpacesItemDecoration(2);
        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        videoList = new ArrayList<>();

上面代码中用到的内部类VodAdapter:

        class VodAdapter extends RecyclerView.Adapter {

        @Override
        public VodItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {
            ViewDataBinding itembinding = DataBindingUtil.inflate(LayoutInflater.from(getContext()
            ), R.layout.vod_list_item, parent, false);
            VodItemViewHolder holder = new VodItemViewHolder(itembinding.getRoot());
            itembinding.setVariable(BR.handler,VodListFragment.this);
            holder.viewDataBinding = itembinding;

            return holder;
        }

        @Override
        public void onBindViewHolder(VodItemViewHolder holder, int position)
        {
            holder.viewDataBinding.setVariable(BR.vodvideo,videoList.get(position));
        }
        @Override
        public int getItemCount()
        {
            return videoList.size();
        }

        class VodItemViewHolder extends RecyclerView.ViewHolder
        {
            public ViewDataBinding viewDataBinding;
            public CardView cardView;
            public VodItemViewHolder(View view)
            {
                super(view);
                cardView = (CardView) view.findViewById(R.id.cardView);
            }
        }
    }
    
用到的内部类SpaceItemDecoration:

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpacesItemDecoration(int space) {
            this.space=space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left=space;
            outRect.right=space;
            outRect.bottom=space;
            if(parent.getChildAdapterPosition(view)

做个简单的说明,如果不加这个SpaceItemDecoration会导致数据第一次加载时的item布局异常。


参考资料:

Android RecyclerView 使用完全解析 体验艺术般的控件:http://blog.csdn.net/lmj623565791/article/details/45059587
RecyclerView实现瀑布流布局: http://blog.csdn.net/tiankong1206/article/details/47088995


你可能感兴趣的:(Coding)