Fragment - removeGlobalOnLayoutListener IllegalStateException

前端 未结 3 1920
一向
一向 2020-12-09 03:35

I\'m trying to get the height and width of an ImageView in a Fragment with the following ViewTreeObserver:

import andr         


        
相关标签:
3条回答
  • 2020-12-09 04:14

    The other solution will work just fine, but it doesn't explain why this is happening.

    There are a few issues to address here:

    GlobalOn VS OnGlobal

    Using the GlobalOn version will give you a deprecation warning, but if you check the source it's just calling the OnGlobal version, so they're equivalent. The difference is that you can only use the OnGlobal one from API Level 16, so if you're targeting an earlier version you'll have to use GlobalOn and deal with that deprecation warning.

    Why is it dead?

    Note that this question is about code in onCreateView, where imageViewPicture is not attached to the view hierarchy yet, it has just been inflated. If you take a quick look at View.getViewTreeObserver() you can see that it creates a "floating" observer in this case. Then when the view is put in the hierarchy dispatchAttachedToWindow is called which then merges the window's and the view's floating observers:

    info.mTreeObserver.merge(mFloatingTreeObserver);
    

    which moves all registered listeners to the window's observer and kills the floating observer.

    The original observer you acquired is the floating one, which is dead, hence calling an add/remove on it results in the above exception.

    Are they the same observers?

    As Danyal, I was also puzzled why removeGlobalOnLayoutListener works on a different observer, but now it's clear with the temporary floating observer. As the floating one is merged to the window's observer the listeners are moved to the other observer, so calling View.getViewTreeObserver() later will give you an observer containing your listener. The new observer is now responsible for handling your listener.

    But it works sometimes!, and another solution

    As to Zordid's comment on why in many cases it's ok to hold on in a local (closure) variable can be explained by a similar reasoning: the just inflated view in onCreateView is not yet attached only a little after it's returned. Most of the you've seen is probably in a method after onCreateView in the lifecycle. float's (OP) solution would work just fine if the observer related code was in onViewCreated. Every lifecycle method has it's own responsibilities, so I would advise splitting the code up like this:

    private ImageView imageViewPicture;
    
    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }
    
    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_general_activity_add_recipe, container, false);
    
        // assuming ... includes:
        this.imageViewPicture = view.findViewById(R.id.image);
    
        return view;
    }
    
    @Override public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    
        final ViewTreeObserver observer = imageViewPicture.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener () {
            @Override public void onGlobalLayout() {
                observer.removeGlobalOnLayoutListener(this);
            }
        });
    }
    

    I also like to wire my other listeners in onViewCreated, this way the number of instance variables are minimized, so imageViewPicture would be a local variable.

    The same is probably true for Activity.setContentView which attaches the inflated view immediately and is usually called in onCreate so the hierarchy is live by the time you play with observers/listeners.

    0 讨论(0)
  • 2020-12-09 04:17

    Better try to check if a getViewTreeObserver is alive. I think the following code will work. Based on https://stackoverflow.com/a/15301092/2914140, https://stackoverflow.com/a/26193736/2914140 and some others.

    ** Update **

    After reading Remove listener from ViewTreeObserver, https://stackoverflow.com/a/40013262/2914140 I rewrote a bit.

    public static void captureGlobalLayout(@NonNull final View view,
                                           @NonNull final ViewTreeObserver.OnGlobalLayoutListener listener) {
        ViewTreeObserver vto = view.getViewTreeObserver();
        if (vto.isAlive()) {
            vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            ViewTreeObserver vto = view.getViewTreeObserver();
                            if (vto.isAlive()) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                    vto.removeOnGlobalLayoutListener(this);
                                } else {
                                    //noinspection deprecation
                                    vto.removeGlobalOnLayoutListener(this);
                                }
                                listener.onGlobalLayout();
                            }
                        }
                    });
        } else {
            view.post(new Runnable() {
                @Override
                public void run() {
                    listener.onGlobalLayout();
                }
            });
    
        }
    }
    

    ** Old answer **

    Strange but even if view.getViewTreeObserver().isAlive() is true, then next call to view.getViewTreeObserver() may again produce the same exception. So, I surrounded a code with try-catch. Possibly you may skip all this and retain only view.post(...) block.

    if (view.getViewTreeObserver().isAlive()) {
        try {
            view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (view.getViewTreeObserver().isAlive()) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        } else {
                            view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        }
                    }
                    yourCode();
                }
            });
        } catch (IllegalStateException e) {
            e.printStackTrace();
            // The same as below branch.
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    view.post(new Runnable() {
                        @Override
                        public void run() {
                            yourCode();
                        }
                    });
                }
            });
        }
    } else {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // Try to wait until the view is ready.
                view.post(new Runnable() {
                    @Override
                    public void run() {
                        yourCode();
                    }
                });
            }
        });
    }
    

    Probably view.post(...) is enough, but I called it from background thread, so if you do the same, better should invoke it from runOnUiThread(new Runnable() ....

    0 讨论(0)
  • 2020-12-09 04:22

    try this :

       ViewTreeObserver observer = imageViewPicture.getViewTreeObserver();
       observer.addOnGlobalLayoutListener (new OnGlobalLayoutListener () {
        @Override
         public void onGlobalLayout() {
    
           imageViewPicture.getViewTreeObserver().removeGlobalOnLayoutListener(this);
          }
        });
    
    0 讨论(0)
提交回复
热议问题