Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between addOnLayoutChangeListener and onLayout(changed)?

Tags:

java

android

I have a class

public class FancyView extends View implements View.OnTouchListener {

I need to get the height/width of the view.

(It could change with, say, device rotation. Also, of course, the height/width is not known at initialization time.)

You can do this...

So, actually within the class FancyView just override onLayout(changed)

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    int hh = getHeight();
    Log.d("~", "Using onLayout(changed), height is known: " +hh);
}

Or, you can do this...

Again within the class FancyView use addOnLayoutChangeListener

private void init() {
    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) {
            Log.d("~", "Using addOnLayoutChangeListener, height is known: " +hh);
        }
    });

}

(Aside: I guess init() is the best place to do that.)

Both seem to work well.

Is there any actual difference between (A) adding a listener with addOnLayoutChangeListener and alternately (B) overriding onLayout(boolean changed ?

Use case: within the class FancyView I draw something on top of the image; so I need to know width/height what size to draw.


Footnote. I've noticed wherever the issue is discussed "Android, get width/height of view" it is often suggested to use onWindowFocusChanged 9as it is "easier"). I really don't see why you'd do that when onLayout(changed) is available; perhaps I'm missing something.

like image 821
Fattie Avatar asked Nov 24 '16 15:11

Fattie


1 Answers

Method addOnLayoutChangeListener is public so it allows to add an external change listener. OTOH onLayout is protected so it's only for internal use.

For internal use my understanding is that both methods provides the same result, but the override is a little cleaner.

Checking source code for View I see that method using change listeners is

public void layout(int l, int t, int r, int b)

This method call internally onLayout and change listeners confirming that both methods are equivalent since they are triggered in the same way. If there is any situation where they are not called at the same time, it may be caused by a bug on the control implementation.

like image 192
Claudio Redi Avatar answered Nov 15 '22 15:11

Claudio Redi