Determine if a view is on screen - Android

后端 未结 2 1780
忘掉有多难
忘掉有多难 2021-02-01 19:46

I\'m a little bit stuck with this one - first and foremost, the following link has been useful however I\'ve come up with a bit of an issue with visibility:

The link: Ch

2条回答
  •  离开以前
    2021-02-01 19:57

    Ok so thanks to OceanLife for pointing me in the right direction! There was indeed a callback required and ViewTreeObserver.OnGlobalLayoutListener() did the trick. I ended up implementing the listener against my fragment class and picked it up where I needed it. Thanks for the warning too regarding the multiple calls, I resolved this using the removeOnGlobalLayoutListener() method - works a charm.

    Code:

    ...
    
    // vto initialised in my onCreateView() method
    
    vto = getView().getViewTreeObserver();
    vto.addOnGlobalLayoutListener(this);
    
    ...
    
    @Override
        public void onGlobalLayout() {
    
            final int i[] = new int[2];
            final Rect scrollBounds = new Rect();
    
            sView.getHitRect(scrollBounds);
            tempView.getLocationOnScreen(i);
    
            if (i[1] >= scrollBounds.bottom) {
                sView.post(new Runnable() {
                    @Override
                    public void run() {
                        sView.smoothScrollTo(0, sView.getScrollY() + (i[1] - scrollBounds.bottom));
                    }
                });
            }
    
            vto.removeOnGlobalLayoutListener(this);
        }
    

    Just got to do some cleaning up now ...

提交回复
热议问题