我已经为使用
我发现如果我在
GridLayoutManager
的RecyclerView
创建了一个自定义的ItemDecoration
。这个ItemDecoration
确保在RecyclerView
中所有子视图之间都应用了相同的间距:
这个ItemDecoration
正如我所希望的那样工作,并且看起来很棒。然而,我注意到在设置RecyclerView
的布局管理器之前需要添加ItemDecoration
。我的主要问题是:为什么会这样?
我正在处理一些遗留代码,它使用CursorLoader
从Web上拉取RSS订阅并将其显示给最终用户。由于某种原因,布局管理器在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);
}
我发现如果我在
onLoadFinished()
中添加我的 ItemDecoration
,那么项目之间的边距看起来比实际要大。@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);
}
上面的截图显示了比我预期更多的边距,因为我只应用了 8dps(card_view_margin
的值)。然而,如果我在 onCreate()
中添加 ItemDecoration
,则它将按预期显示:
@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);
...
}
所以为什么这很重要?为什么在应用布局管理器到我的RecyclerView之前需要添加ItemDecoration
?我确信这与事情在幕后执行的顺序有关。任何形式的解释都将不胜感激:)
如果有人对我如何创建ItemDecoration
感兴趣,可以参考以下内容:
onLoadFinished()
由于某种原因被调用了至少两次。对我来说仍然不完全合理,因为我认为CursorLoader
应该只调用此方法一次......但这超出了我的问题范围,它更多地与我正在处理的旧代码有关。感谢您在此方面的指导 :) - coolDude