我为使用ItemDecorationRecyclerView创建了自定义GridLayoutManagerItemDecoration基本上确保在RecyclerView中应用所有子视图之间的等效间距:
android - LayoutManager之前的ItemDecoration?-LMLPHP
ItemDecoration正按我所希望的那样工作,我认为它看起来很棒。但是,我注意到在为我的ItemDecoration设置布局管理器之前,我需要添加RecyclerView。我的主要问题是:为什么?
我正在处理一些遗留代码,这些代码使用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);
}

我注意到,如果我在ItemDecoration内添加我的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);

    // Adding the custom ItemDecoration
    EqualOffsetItemDecoration itemDecoration = new EqualOffsetItemDecoration(this, R.dimen.card_view_margin, mColumnCount);
    mRecyclerView.addItemDecoration(itemDecoration);
}

android - LayoutManager之前的ItemDecoration?-LMLPHP
上面的屏幕截图显示的边距远远超出我的预期,因为我只应用8dps(值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?我敢肯定这和事情在幕后的执行顺序有关。任何形式的解释都非常感谢:)
仅供参考,如果有人对我如何创建ItemDecoration感兴趣,这里是:
https://github.com/mikepalarz/XYZReader/blob/master/app/src/main/java/com/example/xyzreader/ui/EqualOffsetItemDecoration.java

最佳答案

有趣的问题,但我不认为这是重要的,如果你设置布局经理之前或之后的项目装饰。两个调用都会导致布局请求。
我猜你不止一次在RecyclerView中添加装饰。由于装饰复合,你会看到一个更大的差距,装饰添加两次(或更多次)而不是只有一次。

09-28 04:49