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).

- 2,169
- 4
- 33
- 59

- 1,905
- 1
- 16
- 20
-
Related: http://stackoverflow.com/questions/32496681/how-to-know-when-data-is-loaded-inside-custom-recyclerview – Daniel Nugent Feb 17 '16 at 19:53
-
Still need to fix the issue? – AndroidStorm Aug 03 '18 at 22:18
-
please check out [this](https://stackoverflow.com/questions/60832798/scrolling-position-of-the-cardview-items-in-recyclerview/#60836007) answer – Zain Mar 24 '20 at 17:19
16 Answers
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.
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);
}
});

- 6,678
- 4
- 38
- 50
-
29this method is called several times and not only when it has finished. It didn't work for me – Juan Saravia Dec 05 '15 at 18:31
-
9@Juancho does it work if you remove the listener after you are done with it on `onGlobalLayout`? – Neon Warge Sep 30 '16 at 02:57
-
8@NeonWarge yes it works removing the listener in the first call, thanks! – Juan Saravia Dec 30 '16 at 16:00
-
3To everyone who are facing issue with this suggestion, andrino is actually correct. As a last line in the onGlobalLayout(), you will need to remove the Listener: recyclerView.getViewTreeObserver().removeOnGlobalLayoutListerner(this); This line will ensure it is called only once and doesn't hang the device. – Ram Iyer May 18 '18 at 07:56
-
1This doesn't work when you start an activity. The recyclerview has to ben shown first. – Displee Jan 14 '20 at 17:02
-
The reason why this Callback cannot be performed from Adapters (and this is my speculation), is because if you look closely in the Adapter design, they first built it with the idea of it being an Observable, meaning many RecyclerViews could make use of the same Adapter. The problem with this is obviously that each RecyclerView::setAdapter should also had required a ViewLifeCycleOwner for the component to be truly Observable, and the List submission could have been possible inside the ViewModel. Somewhere in developement they stepped back, but now the View is inaccessible from the Adapter. – Delark Jul 12 '21 at 00:10
Working modification of @andrino anwser.
As @Juancho pointed in comment above. This method is called several times. In this case we want it to be triggered only once.
Create custom listener with instance e.g
private RecyclerViewReadyCallback recyclerViewReadyCallback;
public interface RecyclerViewReadyCallback {
void onLayoutReady();
}
Then set OnGlobalLayoutListener
on your RecyclerView
recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (recyclerViewReadyCallback != null) {
recyclerViewReadyCallback.onLayoutReady();
}
recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
after that you only need implement custom listener with your code
recyclerViewReadyCallback = new RecyclerViewReadyCallback() {
@Override
public void onLayoutReady() {
//
//here comes your code that will be executed after all items are laid down
//
}
};

- 1,572
- 1
- 22
- 31
-
At which point should you initialize "recyclerViewReadyCallback " and implement the listener? – Bisonfan95 May 09 '19 at 21:23
-
I'd do it before setting OnGlobalLayoutListener on RecyclerView, so I am sure that if recycler calls onGlobalLayout() my listener is ready to handle action – Phate P May 10 '19 at 07:50
If you use Kotlin, then there is a more compact solution.
Sample from here.
This layout listener is usually used to do something after a View is measured, so you typically would need to wait until width and height are greater than 0.
... it can be used by any object that extends View and also be able to access to all its specific functions and properties from the listener.
// define 'afterMeasured' layout listener:
inline fun <T: View> T.afterMeasured(crossinline f: T.() -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (measuredWidth > 0 && measuredHeight > 0) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
f()
}
}
})
}
// using 'afterMeasured' handler:
myRecycler.afterMeasured {
// do the scroll (you can use the RecyclerView functions and properties directly)
// ...
}

- 802
- 10
- 16
-
15The article you linked to has been updated - if you are using the android-ktx library, you can simply do `recyclerView.doOnNextLayout { ... }` – James Dec 06 '18 at 23:21
-
3I think you still need OnGlobalLayoutListener because you are observing the changes from RecyclerView's children views. And the listener triggered for the view's tree changes, while doOnNextLayout which uses OnLayoutChangeListener only observe the view itself's change. – Arst Nov 23 '19 at 14:14
-
2I tried to use the doOnNextLayout{}, but for some reason it was called earlier than required. But it came in handy for the case when you need to call an action after positioning all elements of the Activity. https://stackoverflow.com/a/64853255/8313316 – Gregory Nov 16 '20 at 06:15
The best way that I found to know when has finished laying down the items was using the LinearLayoutManager.
For example:
private RecyclerView recyclerView;
...
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false){
@Override
public void onLayoutCompleted(RecyclerView.State state) {
super.onLayoutCompleted(state);
// TODO
}
);
...

- 662
- 8
- 12
-
5Out of all the above, this is the solution that worked for me best. Kotlin way is the following val linearLayoutManager = object : LinearLayoutManager(baseContext, VERTICAL, false) { override fun onLayoutCompleted(state: RecyclerView.State?) { super.onLayoutCompleted(state) //TODO: } } – AbuMaaiz Jan 25 '21 at 09:56
-
-
6
I improved the answer of android developer to fix this problem. It's a Kotlin code but should be simple to understand even if you know only Java.
I wrote a subclass of LinearLayoutManager
which lets you listen to the onLayoutCompleted()
event:
/**
* This class calls [mCallback] (instance of [OnLayoutCompleteCallback]) when all layout
* calculations are complete, e.g. following a call to
* [RecyclerView.Adapter.notifyDataSetChanged()] (or related methods).
*
* In a paginated listing, we will decide if load more needs to be called in the said callback.
*/
class NotifyingLinearLayoutManager(context: Context) : LinearLayoutManager(context, VERTICAL, false) {
var mCallback: OnLayoutCompleteCallback? = null
override fun onLayoutCompleted(state: RecyclerView.State?) {
super.onLayoutCompleted(state)
mCallback?.onLayoutComplete()
}
fun isLastItemCompletelyVisible() = findLastCompletelyVisibleItemPosition() == itemCount - 1
interface OnLayoutCompleteCallback {
fun onLayoutComplete()
}
}
Now I set the mCallback
like below:
mLayoutManager.mCallback = object : NotifyingLinearLayoutManager.OnLayoutCompleteCallback {
override fun onLayoutComplete() {
// here we know that the view has been updated.
// now you can execute your code here
}
}
Note: what is different from the linked answer is that I use onLayoutComplete()
which is only invoked once, as the docs say:
void onLayoutCompleted (RecyclerView.State state)
Called after a full layout calculation is finished. The layout calculation may include multiple
onLayoutChildren(Recycler, State)
calls due to animations or layout measurement but it will include only oneonLayoutCompleted(State)
call. This method will be called at the end oflayout(int, int, int, int)
call.This is a good place for the LayoutManager to do some cleanup like pending scroll position, saved state etc.

- 6,405
- 16
- 66
- 120
-
-
@YonkoKilasi mLayoutManager is an instance of `NotifyingLinearLayoutManager`. – Sufian Feb 18 '20 at 16:25
-
what's the point of isLastItemCompletelyVisible()? its unused in ur example – DennisVA Feb 04 '21 at 00:28
-
I tried this and it worked for me. Here is the Kotlin extension
fun RecyclerView.runWhenReady(action: () -> Unit) {
val globalLayoutListener = object: ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
action()
viewTreeObserver.removeOnGlobalLayoutListener(this)
}
}
viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener)
}
then call it
myRecyclerView.runWhenReady {
// Your action
}

- 1,219
- 10
- 17
-
-
This is the same way as in the answer above: https://stackoverflow.com/a/52492441/8313316 – Gregory Nov 16 '20 at 05:30
-
1You can generalize the extension function to be over View, this should work with other views too. – Amr May 10 '22 at 06:23
Also in same cases you can use RecyclerView.post()
method to run your code after list/grid items are popped up. In my cases it was pretty enough.

- 1,681
- 1
- 13
- 11
-
3This technique works great for scrolling to the currently selected view of a recyclerview GridLayoutManager with dynamic autofit. After I set the adapter: **recyclerView.setAdapter(adapter);** I put: **recyclerView.post(new Runnable() { @Override public void run() { recyclerView.scrollToPosition(currentSelected); } });** And, it works wonderfully (currentlySelected is where I keep the position information)! PavelGP Nice catch. – Trasd Feb 13 '20 at 20:33
I have been struggling with trying to remove OnGlobalLayoutListener
once it gets triggered but that throws an IllegalStateException
. Since what I need is to scroll my recyclerView to the second element what I did was to check if it already have children and if it is the first time this is true, only then I do the scroll:
public class MyActivity extends BaseActivity implements BalanceView {
...
private boolean firstTime = true;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
ViewTreeObserver vto = myRecyclerView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (myRecyclerView.getChildCount() > 0 && MyActivity.this.firstTime){
MyActivity.this.firstTime = false;
scrollToSecondPosition();
}
}
});
}
...
private void scrollToSecondPosition() {
// do the scroll
}
}
HTH someone!
(Of course, this was inspired on @andrino and @Phatee answers)

- 2,473
- 4
- 20
- 32
This is how I did it
recyclerView.setLayoutManager(new LinearLayoutManager(this){
@Override
public void onLayoutCompleted(RecyclerView.State state) {
super.onLayoutCompleted(state);
//code to run after loading recyclerview
new GuideView.Builder(MainActivity.this)
.setTargetView(targetView)
.setGravity(Gravity.auto)
.setDismissType(DismissType.outside)
.setContentTextSize(18)
.build()
.show();
}
});
I wish this will help you.

- 87
- 9
-
1`onLayoutCompleted` will be called multiple times, I would avoid using this – marticztn Aug 06 '22 at 19:33
Here is an alternative way:
You can load your recycler view in a thread. Like this
First, create a TimerTask
void threadAliveChecker(final Thread thread){
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if(!thread.isAlive()){
runOnUiThread(new Runnable() {
@Override
public void run() {
// stop your progressbar here
}
});
}
}
},500,500);
}
Second, create a runnable
Runnable myRunnable = new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
// load recycler view from here
// you can also toast here
}
});
}
};
Third, create a thread
Thread myThread = new Thread(myRunnable);
threadAliveChecker();
// start showing progress bar according to your need (call a method)
myThread.start();
Understanding the above code now:
TimerTask - It will run and will check the thread (every 500 milliseconds) is running or completed.
Runnable - runnable is just like a method, here you have written the code that is needed to be done in that thread. So our recycler view will be called from this runnable.
Thread - Runnable will be called using this thread. So we have started this thread and when the recyclerView load (runnable code load) then this thread will be completed (will not live in programming words).
So our timer is checking the thread is alive or not and when the thread.isAlive is false then we will remove the progress Bar.

- 1,163
- 8
- 22
If you are using the android-ktx library and if you need to perform an action after positioning all elements of the Activity, you can use this method:
// define 'afterMeasured' Activity listener:
fun Activity.afterMeasured(f: () -> Unit) {
window.decorView.findViewById<View>(android.R.id.content).doOnNextLayout {
f()
}
}
// in Activity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(...)
afterMeasured {
// do something here
}
}

- 802
- 10
- 16
You can use with this approach
if ((adapterPosition + 1) == mHistoryResponse.size) {
Log.d("debug", "process done")
}
get the adapterPosition with plus 1 and check it with your data classes size, if it has same size, the process is practically complete.

- 1
- 1
For those that are not using Kotlin and are still struggling, I took a fast look at the doOnNextLayout(crossinline action: (view: T) -> Unit) solution they implemented, and it is pretty simple.
IF you are NOT working with a custom RecyclerView (CustomRecyclerView extends RecyclerView
), you may want to rethink it as this will bring a lot of benefits you may want to add in the future (smooth scroll to position, vertical dividers, etc..)
Inside the CustomRecyclerView.class
public void doOnNextLayout(Consumer<List<View>> onChange) {
addOnLayoutChangeListener(
new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
onChange.accept(getChildren());
removeOnLayoutChangeListener(this);
}
}
);
}
The getChildren()
method is building a List of size getChildCount(); and a add(getChild(i)) on each iteration.
Now...
One important aspect about the code is this: removeOnLayoutChangeListener(this);
This means that the devs are asking for you to execute this before each list submission to the adapter.
In theory we could only place the listener ONCE upon RecyclerView creation (which IMO would be cheaper/better) + because we are retrieving the views, we could retrieve their respective binds with DataBindingUtils. and get whatever data the adapter gave the view onBind via their DataBind.
To do this tho it requires more code.
First the adapter needs to be aware of the Fragment they inhabit, OR the RecyclerView::setAdapter needs to provide a ViewLifeCyclerOwner, a third easier option is to provide the adapter with a onViewDestroy() method, and execute it on Fragment's onDestroyView() method.
@Override
public void onDestroyView() {
super.onDestroyView();
adater.onViewDestroyed();
}
by overriding the onAttachedToRecyclerView, we are able to attach them as observers.
private final List<Runnable> submitter = new ArrayList<>();
@Override
public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
if (recyclerView instanceof CustomRecyclerView) {
submitter.add(((CustomRecyclerView) recyclerView)::onSubmit);
}
}
Where the onSubmit method on the CustomRecyclerView side will provide a boolean that will tell the recyclerView whether a list is being submitted.
private boolean submitting;
public void doOnNextLayout(Consumer<List<View>> onChange) {
addOnLayoutChangeListener(
(v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
if (submitting) {
onChange.accept(getChildren());
submitting = false;
}
}
);
}
public void onSubmit() {
submitting = true;
}
Each Runnable will be executed at the moment of list submission:
In the case of the ListAdapter there are 2 possible entry points:
private void notifyRVs() {
for (Runnable r:submitter
) {
r.run();
}
}
@Override
public void submitList(@Nullable List<X> list, @Nullable Runnable commitCallback) {
notifyRVs();
super.submitList(list, commitCallback);
}
@Override
public void submitList(@Nullable List<X> list) {
notifyRVs();
super.submitList(list);
}
Now to prevent memory leaks we must clear the List of Runnables on ViewDestroyed() inside the Adapter...
public void onViewDestroyed() {
submitter.clear();
}
Now because the functionality of the method changed we should rename it, and decouple the Consumer<List> from the LayoutChangeListener()
private Consumer<List<View>> onChange = views -> {};
public void setOnListSubmitted(Consumer<List<View>> onChange) {
this.onChange = onChange;
}
public CustomRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
//Read attributes
setOnListSubmissionListener();
}
private void setOnListSubmissionListener() {
addOnLayoutChangeListener(
(v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
if (submitting) {
onChange.accept(getChildren());
submitting = false;
}
}
);
}

- 1,141
- 2
- 9
- 15
What worked for me was to add the listener after setting the RecyclerView adapter.
ServerRequest serverRequest = new ServerRequest(this);
serverRequest.fetchAnswersInBackground(question_id, new AnswersDataCallBack()
{
@Override
public void done(ArrayList<AnswerObject> returnedListOfAnswers)
{
mAdapter = new ForumAnswerRecyclerViewAdapter(returnedListOfAnswers, ForumAnswerActivity.this);
recyclerView.setAdapter(mAdapter);
recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
progressDialog.dismiss();
}
});
}
});
This dismisses the "progressDialog" after the global layout state or the visibility of views within the view tree changes.

- 1,550
- 15
- 14
// Another way
// Get the values
Maybe<List<itemClass>> getItemClass(){
return /* */
}
// Create a listener
void getAll(DisposableMaybeObserver<List<itemClass>> dmo) {
getItemClass().subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(dmo);
}
// In the code where you want to track the end of loading in recyclerView:
DisposableMaybeObserver<List<itemClass>> mSubscriber = new DisposableMaybeObserver<List<itemClass>>() {
@Override
public void onSuccess(List<itemClass> item_list) {
adapter.setWords(item_list);
adapter.notifyDataSetChanged();
Log.d("RECYCLER", "DONE");
}
@Override
public void onError(Throwable e) {
Log.d("RECYCLER", "ERROR " + e.getMessage());
}
@Override
public void onComplete() {
Log.d("RECYCLER", "COMPLETE");
}
};
void getAll(mSubscriber);
//and
@Override
public void onDestroy() {
super.onDestroy();
mSubscriber.dispose();
Log.d("RECYCLER","onDestroy");
}

- 97
- 1
- 10
recyclerView.getChildAt(recyclerView.getChildCount() - 1).postDelayed(new Runnable() {
@Override
public void run() {
//do something
}
}, 300);
RecyclerView only lays down specific number of items at a time, we can get the number by calling getChildCount(). Next, we need to get the last item by calling getChildAt (int index). The index is getChildCount() - 1.
I'm inspired by this person answer and I can't find his post again. He said it's important to use postDelayed() instead of regular post() if you want to do something to the last item. I think it's to avoid NullPointerException. 300 is delayed time in ms. You can change it to 50 like that person did.

- 11
- 4