Android开发 RecyclerView开发记录

Posted 观心静

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android开发 RecyclerView开发记录相关的知识,希望对你有一定的参考价值。

将RecyclerView高度,在有指定数量item后固定

使用时,请注意2点情况

  1. 不要将RecyclerView的android:layout_height属性设置为wrap_content,不然是不会成功的.
  2. item的根布局也需要固定高度,不要使用wrap_content,否则下面测算高度时会出现不准确的情况.
    /**
     * 自适应列表View在到指定数量item后固定高度,
     *
     * @param targetNum
     */
    private void adaptiveRecyclerViewHeight(int targetNum) {
        mFamilyListRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()) {
            @Override
            public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
                int count = state.getItemCount();
                if (count > 0) {
                    if (count > targetNum) {
                        count = targetNum;
                    }
                    int realHeight = 0;
                    int realWidth = 0;
                    for (int i = 0; i < count; i++) {
                        View view = recycler.getViewForPosition(0);
                        if (view != null) {
                            measureChild(view, widthSpec, heightSpec);
                            int measuredWidth = View.MeasureSpec.getSize(widthSpec);
                            int measuredHeight = view.getMeasuredHeight();
                            realWidth = realWidth > measuredWidth ? realWidth : measuredWidth;
                            realHeight = realHeight + measuredHeight;
                        }
                    }
                    setMeasuredDimension(realWidth, realHeight);
                } else {
                    super.onMeasure(recycler, state, widthSpec, heightSpec);
                }
            }
        });
    }

 

 

 

 

 

END

以上是关于Android开发 RecyclerView开发记录的主要内容,如果未能解决你的问题,请参考以下文章

Android开发,为啥RecyclerView没有显示数据

RecyclerView的使用(Android开发必备,替换掉ListView)

android开发学习 ------- RecyclerView多类型实例

Android开发 RecyclerView实现拖动与滑动ItemTouchHelper

Android开发 RecyclerView实现拖动与滑动ItemTouchHelper

Android开发之漫漫长途 XIV——RecyclerView