How to build a Horizontal ListView with RecyclerView?

前端 未结 13 1248
小鲜肉
小鲜肉 2020-11-22 04:53

I need to implement a horizontal listview in my Android application. I did a bit of research and came across How can I make a horizontal ListView in Android? and Horizontal

13条回答
  •  野的像风
    2020-11-22 05:37

    If you wish to use the Horizontal Recycler View to act as a ViewPager then it's possible now with the help of LinearSnapHelper which is added in Support Library version 24.2.0.

    Firstly Add RecyclerView to your Activity/Fragment

    
        
    

    In my case I have used a CardView inside the RecyclerView

    blog_row.xml

    
    
    
            
    
                
    
                
    
                
            
    
        
    

    In your Activity/Fragment

        private RecyclerView mBlogList;
    
    
    
    
     LinearLayoutManager layoutManager
                        = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
                mBlogList = (RecyclerView) findViewById(R.id.blog_list);
    
                mBlogList.setHasFixedSize(true);
                mBlogList.setLayoutManager(layoutManager);
    
    LinearSnapHelper snapHelper = new LinearSnapHelper() {
                @Override
                public int findTargetSnapPosition(RecyclerView.LayoutManager lm, int velocityX, int velocityY) {
                    View centerView = findSnapView(lm);
                    if (centerView == null)
                        return RecyclerView.NO_POSITION;
    
                    int position = lm.getPosition(centerView);
                    int targetPosition = -1;
                    if (lm.canScrollHorizontally()) {
                        if (velocityX < 0) {
                            targetPosition = position - 1;
                        } else {
                            targetPosition = position + 1;
                        }
                    }
    
                    if (lm.canScrollVertically()) {
                        if (velocityY < 0) {
                            targetPosition = position - 1;
                        } else {
                            targetPosition = position + 1;
                        }
                    }
    
                    final int firstItem = 0;
                    final int lastItem = lm.getItemCount() - 1;
                    targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem));
                    return targetPosition;
                }
            };
            snapHelper.attachToRecyclerView(mBlogList);
    

    Last Step is to set adapter to RecyclerView

    mBlogList.setAdapter(firebaseRecyclerAdapter);
    

提交回复
热议问题