RecyclerView IndexOutOfBoundsException 引出的RecyclerView 的使用方法总结
2016-05-31 10:19
1261 查看
在弹出框中使用RecyclerView 展示一个列表,其中弹出框的高度要随着列表数目的高度变化。
这个需求有两种解决方案:
注意高亮代码,要判定这个itemCount,不然 recycler.getViewForPosition(0)就会报IndexOutOfBoundsException错误。
int spanCount, int orientation
注意使用写法的顺序。在setAdapter之后。
这个需求有两种解决方案:
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));
相关文章推荐
- 136. Single Number
- typeof关键字是C语言的应用
- Java读取Properties文件的七种方法
- java 初始化
- 2016第七届美国新泽西国际武术锦标赛五月底在大西洋城开赛
- 目诊知识2
- linux进程通信--消息队列
- WebClient 用法小结
- windows 用户登录和注销监控|windows session 状态改变监控
- tomcat端口配置文件解析
- 斯坦福机器学习公开课笔记
- IOS indexPathsForVisibleItems原理
- 用DeflateStream和GZipStream压缩数据
- spring-两个对象之间的属性拷贝工具
- UITextField点击选中文字
- 编程风格规范google版
- IOS-WebViewJavascriptBridge使用说明
- android 跳转到当前应用的详情页面
- javascript实现任务栏消息提示的简单实例
- 强悍的 Linux —— tar.xz 文件的解压