在Android開發(fā)需求中本辐,通常會遇到一種需求破讨,然后在Scrollview這樣的滾動View中包含Recyclerview等具有動態(tài)變化高度的組件砂蔽,于是就開始各種百度碑定,然而流码,網(wǎng)上給到的方法:
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方法調(diào)用的時候,adapter中的item還是為0漫试,于是會報:
java.lang.IndexOutOfBoundsException: Invalid item position 0(0). Item count:0
最終采用方法:
在Recyclerview組件外直接包裹一層RelativeLayout六敬,不需要那些個廢代碼,實(shí)現(xiàn)了此功能驾荣。
<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()));
作筆記外构。