关于RecyclerView的宽高调整

设置ItemView的间隔高宽

重写ItemDecoration的getItemOffsets函数即可:

recycleview.addItemDecoration(new RecyclerView.ItemDecoration() {
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.set(4, 4, 4, 4);//设置itemView中内容相对边框左,上,右,下距离
    }
});

ItemView适应RecyclerView

RecyclerView大小固定的情况下,根据RecyclerView的宽高设置ItemView的宽高,以达到recyclerview刚好显示N行/列数据的目的:
在原理是先计算出RecyclerView的宽高,然后在Adapter的onCreateViewHolder中设置view的高度:
比如一个垂直列表,希望recyclerview刚好显示三行,这样写:

@Override
public ClubServiceAdapter.ServiceItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(布局文件, parent, false);
    view.getLayoutParams().height = mRecyclerViewHeight/3;
    return new ServiceItemViewHolder(view);
}

RecyclerView适应ItemView

ItemView大小固定的情况下,根据ItemView的宽高调整recyclerview的宽高,以达到recyclerview刚好显示N行/列数据的目的:
原理是重写LayoutManager的onMeasure方法,计算itemview的宽高,进而计算出recyclerview的宽高。
比如,一个垂直列表,希望recyclerview刚好显示三行,这样写:

recyclerView.setLayoutManager(new LinearLayoutManager(this) {
    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
        if (getChildCount() > 0) {
            View firstChildView = recycler.getViewForPosition(0);
            measureChild(firstChildView, widthSpec, heightSpec);
            setMeasuredDimension(View.MeasureSpec.getSize(widthSpec), firstChildView.getMeasuredHeight()*3);
        } else {
            super.onMeasure(recycler, state, widthSpec, heightSpec);
        }
    }
});

你可能感兴趣的:(Android)