How to have RecyclerView snapped to center and yet be able to scroll to all items, while the center is “selected”?

前端 未结 2 1724
心在旅途
心在旅途 2021-02-03 15:27

Background

I\'m try to achieve something similar to what the Camera app has for its modes:

I might probably not need to have a ViewPager, as seems tha

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-03 15:57

    This is how i solved it. The problem on custom snaphelper and decorators is that they dont work with other libaries and custom Views. It also works with items with variable widths.

    If you want to snap the items, just use the classic snaphelper on the recyclerview

    public class CenterRecyclerView extends RecyclerView {
    
        public CenterRecyclerView(@NonNull Context context) {
            super(context);
        }
    
        public CenterRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
        }
    
        public CenterRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        public void updatePadding() {
            post(() -> {
                final DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
                final int screenWidth = displayMetrics.widthPixels;
                final int screenHeight = displayMetrics.heightPixels;
    
                ViewHolder firstViewHolder = findViewHolderForAdapterPosition(0);
                if (firstViewHolder != null) {
                    firstViewHolder.itemView.measure(WRAP_CONTENT, WRAP_CONTENT);
                    int viewWidth = firstViewHolder.itemView.getMeasuredWidth();
                    int padding;
                    if (screenHeight > screenWidth) {
                        //Portrait
                        padding = screenWidth / 2 - viewWidth / 2;
                    } else {
                        //Landscape
                        padding = screenHeight / 2 - viewWidth / 2;
                    }
                    setPadding(padding, 0, padding, 0);
                } else {
                    Log.e("CenterRecyclerView", "Could not get first ViewHolder");
                }
            });
        }
    
        @Override
        protected void onFinishInflate() {
            super.onFinishInflate();
            updatePadding();
        }
    
        @Override
        protected void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            updatePadding();
        }
    }
    

提交回复
热议问题