问题
I am trying to update a thumbnail image once the view is initialized and knows its sizes
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View pagerView = inflater.inflate(R.layout.fragment_reference, container, false);
......
mPhotoView = pagerView.findViewById(R.id.reference_photo);
mPhotoView.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
Log.d(TAG,"Reference Pager PhotoView Layout Change."+" left: "+left+" top: "+top+" right: "+right+ " bottom: "+bottom);
updatePhotoView();
});
......
}
but Logcat shows it has been called four times in a row:
Reference Pager PhotoView Layout Change. left: 0 top: 0 right: 720 bottom: 436
Reference Pager PhotoView Layout Change. left: 0 top: 0 right: 720 bottom: 436
Skipped 59 frames! The application may be doing too much work on its main thread.
Reference Pager PhotoView Layout Change. left: 0 top: 0 right: 720 bottom: 436
Reference Pager PhotoView Layout Change. left: 0 top: 0 right: 720 bottom: 436
What causes that to happen? How do I avoid that?
回答1:
What causes that to happen?
You never removed the listener. This results in onLayoutChange()
being invoked multiple times. Call removeOnLayoutChangeListener()
on the view as follows:
mPhotoView.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
v.removeOnLayoutChangeListener(this); // this prevents the callback to be invoked multiple times
Log.d(TAG,"Reference Pager PhotoView Layout Change."+" left: "+left+" top: "+top+" right: "+right+ " bottom: "+bottom);
updatePhotoView();
});
来源:https://stackoverflow.com/questions/55142197/onlayoutchange-called-too-many-times