12

In Android, can you create a Listener for catching changes in a View's properties (width / height / margin / position relative to top of the screen)?

I want to trigger an event when layout_marginTop="10dp" is changed to a different value.

Jack
  • 430
  • 2
  • 5
  • 19
  • You can try "OnLayoutChangeListener" but be careful: it listening almost EVERYTHING and sometimes does it twice :) And yes, better late than never - so hello from 2021 ;) – kazuser May 13 '21 at 15:09

1 Answers1

25

What about implementing a OnLayoutChangeListener that gets called when a View is moved due to Layout Change

new View().addOnLayoutChangeListener(new OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
                    int oldTop, int oldRight, int oldBottom) {
        // TODO Auto-generated method stub  
    }
});

Excerpt from Android API:

Add a listener that will be called when the bounds of the view change due to layout processing.

chuck258
  • 912
  • 7
  • 16
  • 1
    Thanks for your answer, but this is not what I am looking for. I want to listen to changes of ALL AVAILABLE properties of the View (padding, margin, width, height, rotation, tag, visibility), not just the changes to the left/top/right/bottom properties. – Jack Oct 08 '13 at 14:32
  • AFAIK the margin doesn't belong to a View. It can be contained in View.getLayoutParams or only be stored in the Parents View. However: Is it an Option to use derived View Classes and add the Listener you want? – chuck258 Oct 08 '13 at 19:08
  • It is a possibility to use derived View Classes, if the method can be implemented on multiple View Class derivatives (e.g. ImageView, TextView). It is not a problem to create extended View Classes of all the View Class derivatives that need to implement a propertyListener for. For example: If I need 2 views (ImageView + TextView) with propertyListeners -> I should create 2 custom View Classes that extend ImageView and TextView. These 2 custom Views have propertyListeners set to them. – Jack Oct 10 '13 at 13:03
  • It is usable for handling view Y changed in adjustResize for detecting keyboard show/hide events? –  Oct 26 '18 at 06:31