LayoutManager之前的ItemDecoration?

时间:2018-02-24 22:03:21

标签: android android-recyclerview

我为使用ItemDecoration的{​​{1}}创建了自定义RecyclerViewGridLayoutManager基本上确保在ItemDecoration内应用所有子视图之间的等效间距:

enter image description here

RecyclerView正如我希望的那样工作,我觉得它看起来很棒。但是,我注意到在为ItemDecoration设置布局管理器之前,我需要添加ItemDecoration。我的主要问题是:为什么会这样?

我正在处理一些遗留代码,这些代码使用RecyclerView从网络中提取RSS Feed并将其显示给最终用户。无论出于何种原因,布局管理器都在CursorLoader中设置:

onLoadFinished()

我注意到,如果我在@Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { Adapter adapter = new Adapter(cursor); adapter.setHasStableIds(true); mRecyclerView.setAdapter(adapter); GridLayoutManager gridLayoutManager = new GridLayoutManager(this, mColumnCount, GridLayoutManager.VERTICAL, false); mRecyclerView.setLayoutManager(gridLayoutManager); } 中添加ItemDecoration,则项目之间的边距看起来比实际应该大:

onLoadFinished()

enter image description here

上面的截图显示了比我预期的更多的余量,因为我只应用了8dps(@Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { Adapter adapter = new Adapter(cursor); adapter.setHasStableIds(true); mRecyclerView.setAdapter(adapter); GridLayoutManager gridLayoutManager = new GridLayoutManager(this, mColumnCount, GridLayoutManager.VERTICAL, false); mRecyclerView.setLayoutManager(gridLayoutManager); // Adding the custom ItemDecoration EqualOffsetItemDecoration itemDecoration = new EqualOffsetItemDecoration(this, R.dimen.card_view_margin, mColumnCount); mRecyclerView.addItemDecoration(itemDecoration); } 的值)。但是,如果我在card_view_margin中添加ItemDecoration,则会按预期显示:

onCreate()

...第一次截图就是这种情况。那为什么这很重要?在将布局管理器应用到@Override protected void onCreate(Bundle savedInstanceState) { ... mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); mColumnCount = getResources().getInteger(R.integer.list_column_count); /* In order to have equal spacing along the edges of the screen as well as between the child views of the RecyclerView, an EqualOffsetItemDecoration is applied to the RecyclerView. */ EqualOffsetItemDecoration itemDecoration = new EqualOffsetItemDecoration(this, R.dimen.card_view_margin, mColumnCount); mRecyclerView.addItemDecoration(itemDecoration); ... } 之前,为什么需要添加ItemDecoration?我确信这与事情在幕后执行的顺序有关。非常感谢任何形式的解释:)

仅供参考,如果有人对我创建RecyclerView的方式感兴趣,请点击此处:

https://github.com/mikepalarz/XYZReader/blob/master/app/src/main/java/com/example/xyzreader/ui/EqualOffsetItemDecoration.java

0 个答案:

没有答案