您的位置:首页 > 其它

RecyclerView IndexOutOfBoundsException 引出的RecyclerView 的使用方法总结

2016-05-31 10:19 1261 查看
在弹出框中使用RecyclerView 展示一个列表,其中弹出框的高度要随着列表数目的高度变化。

这个需求有两种解决方案:

1.自定义一个LinearLayoutManager ,动态修改RecyclerView 的布局高度

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
* Created by lengqi on 2016/3/18.
*/
public class AutoHightLinearLayoutManager extends LinearLayoutManager {

private int size;

public AutoHightLinearLayoutManager(Context context, int sizeParam) {
super(context);
size = sizeParam;
}

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
'''  int count = state.getItemCount();'''
'''   if (count > 0) { '''
View view = recycler.getViewForPosition(0);
if (view != null) {
measureChild(view, widthSpec, heightSpec);
int measuredWidth = View.MeasureSpec.getSize(widthSpec);
int measuredHeight = view.getMeasuredHeight();
setMeasuredDimension(measuredWidth, measuredHeight * size);
}
'''   } else { '''
'''  super.onMeasure(recycler, state, widthSpec, heightSpec); '''
''' } '''
}
}


注意高亮代码,要判定这个itemCount,不然 recycler.getViewForPosition(0)就会报IndexOutOfBoundsException错误。

2. 使用StaggeredGridLayoutManager

new StaggeredGridLayoutManager(modeList.size(), StaggeredGridLayoutManager.HORIZONTAL)


int spanCount, int orientation

注意使用写法的顺序。在setAdapter之后。

RecyclerView mModeView = (RecyclerView) window.findViewById(R.id.rv_speed_modes);

modeAdapter = new ModeAdapter(modeList);
mModeView.setAdapter(modeAdapter);
modeAdapter.notifyDataSetChanged();
mModeView.setLayoutManager(new StaggeredGridLayoutManager(modeList.size(), StaggeredGridLayoutManager.HORIZONTAL));
mModeView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: