onLayoutChange()被调用太多次

时间:2019-03-13 12:42:30

标签: android android-layout

视图初始化后,我尝试更新缩略图,并知道其大小

@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();
    });
       ......
}

但是 Logcat 显示它已被连续调用四次:

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

什么原因导致这种情况发生?我该如何避免?

1 个答案:

答案 0 :(得分:0)

  

什么原因导致这种情况发生?

您从未删除监听器。这导致onLayoutChange()被多次调用。在视图上调用removeOnLayoutChangeListener(),如下所示:

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