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

来源:互联网 发布:数据专业问答题 编辑:程序博客网 时间:2024/06/04 23:19

在弹出框中使用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));
1 0
原创粉丝点击