butterknife icon indicating copy to clipboard operation
butterknife copied to clipboard

Feature request: ViewTreeObserver

Open jonasfa opened this issue 11 years ago • 7 comments

Add support for ViewTreeObserver listeners:

  • onScroll
  • onLayout
  • onDraw
  • etc

See: https://developer.android.com/reference/android/view/ViewTreeObserver.html

jonasfa avatar Aug 15 '14 02:08 jonasfa

What do you envision this looking like?

JakeWharton avatar Aug 15 '14 02:08 JakeWharton

@OnScroll(R.id.scroll_view)
void syncFloatingView() {
}

instead of

scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
    public void onScrollChanged() {
    }
});

jonasfa avatar Aug 15 '14 02:08 jonasfa

@OnLayout(R.id.bottom_button)
void updateGoogleMapBottomPadding() {
}

instead of

bottomButton.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    public void onGlobalLayout() {
    }
});

jonasfa avatar Aug 15 '14 02:08 jonasfa

The ids on the annotations are unnecessary, it's the same observer for the entire view tree. Not sure this is a good idea tho. E.g. for a scrollview you generally wouldn't want to be notified of any scroll. ViewTreeObserver is not that widely used, and adding annotations could encourage people to use it for the wrong reasons.

SimonVT avatar Aug 15 '14 13:08 SimonVT

@SimonVT I agree it's not ideal to get all scrolling notifications. The problem is there isn't any other option as View/ScrollView doesn't provide a scroll listener. On the other hand, Layout notifications would be great to set up padding for layouts with floating views. Ie: to set a MapView bottomPadding to match a floating button's height. See: https://developers.google.com/maps/documentation/android/map#map_padding

jonasfa avatar Aug 15 '14 14:08 jonasfa

It's better to subclass ScrollView and create your own lister than to use ViewTreeObserver. If you want to get notified of a View being laid out, there's View#OnLayoutChangeListener. There's not really a lot of reasons to use ViewTreeObserver in your average app.

SimonVT avatar Aug 15 '14 14:08 SimonVT

Good point, but ButterKnife doesn't have an annotation for View.OnLayoutChangeListener yet. Should we open an issue to discuss it?

Also, View.OnLayoutChangeListener is unfortunately API 11+ only. I know Gingerbread is almost dead, but it's not dead yet. It's probably dead enough to keep using ViewTreeObserver manually for a litle longer though?

jonasfa avatar Aug 15 '14 14:08 jonasfa