如何知道回收视图何时完成了项目的放置?

我有一个 RecyclerViewCardView里面。在 CardView有一个500分钟的高度,但我想缩短这个高度,如果 RecyclerView是较小的。 所以我想知道当 RecyclerView第一次完成放下它的项目时,是否有任何监听器被调用,使得 RecyclerView的高度可以设置为 CardView的高度(如果小于500dp)。

73840 次浏览

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);
}
});

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.

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
//
}
};

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)

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

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.

// 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");
}
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.

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 one onLayoutCompleted(State) call. This method will be called at the end of layout(int, int, int, int) call.

This is a good place for the LayoutManager to do some cleanup like pending scroll position, saved state etc.

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:

  1. TimerTask - It will run and will check the thread (every 500 milliseconds) is running or completed.

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

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

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
}

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
}
}

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
}
);


...

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.

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;
}
}
);
}

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.