gpt4 book ai didi

android - LayoutManager 之前的 ItemDecoration?

转载 作者:搜寻专家 更新时间:2023-11-01 09:28:43 25 4
gpt4 key购买 nike

我为使用 GridLayoutManagerRecyclerView 创建了自定义 ItemDecorationItemDecoration 本质上确保在 RecyclerView 中应用所有 subview 之间的等效间距:

enter image description here

ItemDecoration 完全按照我希望的方式工作,我认为它看起来很棒。但是,我注意到在为我的 RecyclerView 设置布局管理器之前,我需要添加 ItemDecoration。我的主要问题是:这是为什么?

我正在处理一些遗留代码,这些代码使用 CursorLoader 从网络中提取 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);
}

enter image description here

上面的屏幕截图显示的边距比我预期的要多得多,因为我只应用了 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 感兴趣,这里是:

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

最佳答案

有趣的问题,但我认为在项目装饰之前或之后设置布局管理器并不重要。这两个调用都会导致布局请求。

我猜测您不止一次向 RecyclerView 添加装饰。由于装饰复合,您会看到装饰添加两次(或更多次)而不是一次的更大差距。

关于android - LayoutManager 之前的 ItemDecoration?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48968085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com