关闭

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

1957人阅读 评论(0) 收藏 举报

在弹出框中使用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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:96397次
    • 积分:2076
    • 等级:
    • 排名:第18531名
    • 原创:109篇
    • 转载:39篇
    • 译文:0篇
    • 评论:10条
    最新评论