onLayoutChange() called too many times

大憨熊 提交于 2021-01-27 13:13:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!