工作生活

RecycleView根据条目数量设置固定高度

2019-07-02  本文已影响0人  见字如晤一

在Android开发需求中,通常会遇到一种需求,然后在Scrollview这样的滚动View中包含Recyclerview等具有动态变化高度的组件,于是就开始各种百度,然而,网上给到的方法:

 LinearLayoutManager exceptionLayoutManager = new LinearLayoutManager(getActivity()) {

            @Override
            public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {

                View view = recycler.getViewForPosition(0);
                if (view != null) {
                    measureChild(view, widthSpec, heightSpec);
                    //int measuredWidth = View.MeasureSpec.getSize(widthSpec);
                    int measuredHeight = view.getMeasuredHeight();
                    int showHeight = measuredHeight * state.getItemCount();
                    if (state.getItemCount() >= 5) {
                        showHeight = measuredHeight * 5;
                    }
                    setMeasuredDimension(widthSpec, showHeight);
                }
            }

            @Override
            public boolean supportsPredictiveItemAnimations() {
                return false;
            }
        };
        exceptionLayoutManager.setAutoMeasureEnabled(true);
        mRecycleView.setHasFixedSize(false);
        mRecycleView.setLayoutManager(exceptionLayoutManager);

会崩溃,因为onMeasure方法调用的时候,adapter中的item还是为0,于是会报:

java.lang.IndexOutOfBoundsException: Invalid item position 0(0). Item count:0

最终采用方法:
在Recyclerview组件外直接包裹一层RelativeLayout,不需要那些个废代码,实现了此功能。

<RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@color/white"
                    android:orientation="vertical"
                    >
                <android.support.v7.widget.RecyclerView
                    android:id="@+id/id_rv_orders"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />

                </RelativeLayout>

Java代码里不需要那些废代码:

homeParkAdapter = new HomeParkAdapter(this.getContext(), mParkCarInfoList);
mRecycleView.setAdapter(homeParkAdapter);
mRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));

作笔记。

上一篇 下一篇

猜你喜欢

热点阅读