何时完成放置项目

何时完成放置项目

本文介绍了如何知道 RecyclerView 何时完成放置项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 RecyclerView 位于 CardView 中.CardView 的高度为 500dp,但如果 RecyclerView 较小,我想缩短此高度.所以我想知道是否有任何监听器在 RecyclerView 第一次完成放下它的项目时被调用,从而可以将 RecyclerView 的高度设置为CardView 的高度(如果小于 500dp).

I have a RecyclerView that is inside a CardView. The CardView has a height of 500dp, but I want to shorten this height if the RecyclerView is smaller.So I wonder if there is any listener that is called when the RecyclerView has finished laying down its items for the first time, making it possible to set the RecyclerView's height to the CardView's height (if smaller than 500dp).

推荐答案

我还需要在我的回收器视图完成所有元素的膨胀后执行代码.我尝试在我的适配器中检查 onBindViewHolder,如果位置是最后一个,然后通知观察者.但此时,回收者视图仍未完全填充.

I also needed to execute code after my recycler view finished inflating all elements. I tried checking in onBindViewHolder in my Adapter, if the position was the last, and then notified the observer. But at that point, the recycler view still was not fully populated.

作为 RecyclerView 实现 ViewGroup这个 anwser 非常有帮助.您只需将 OnGlobalLayoutListener 添加到回收者视图:

As RecyclerView implements ViewGroup, this anwser was very helpful. You simply need to add an OnGlobalLayoutListener to the recyclerView:

View recyclerView = findViewById(R.id.myView);
recyclerView
    .getViewTreeObserver()
    .addOnGlobalLayoutListener(
        new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // At this point the layout is complete and the
                // dimensions of recyclerView and any child views
                // are known.
                recyclerView
                    .getViewTreeObserver()
                    .removeOnGlobalLayoutListener(this);
            }
        });

这篇关于如何知道 RecyclerView 何时完成放置项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 02:03