How to detect a layout resize?

cottonBallPaws picture cottonBallPaws · Nov 13, 2010 · Viewed 41.6k times · Source

Dianne Hackborn mentioned in a couple threads that you can detect when a layout as been resized, for example, when the soft keyboard opens or closes. Such a thread is this one... http://groups.google.com/group/android-developers/browse_thread/thread/d318901586313204/2b2c2c7d4bb04e1b

However, I didn't understand her answer: "By your view hierarchy being resized with all of the corresponding layout traversal and callbacks."

Does anyone have a further description or some examples of how to detect this? Which callbacks can I link into in order to detect this?

Thanks

Answer

Michael Allan picture Michael Allan · Dec 24, 2015

One way is View.addOnLayoutChangeListener. There's no need to subclass the view in this case. But you do need API level 11. And the correct calculation of size from bounds (undocumented in the API) can sometimes be a pitfall. Here's a correct example:

view.addOnLayoutChangeListener( new View.OnLayoutChangeListener()
{
    public void onLayoutChange( View v,
      int left,    int top,    int right,    int bottom,
      int leftWas, int topWas, int rightWas, int bottomWas )
    {
        int widthWas = rightWas - leftWas; // Right exclusive, left inclusive
        if( v.getWidth() != widthWas )
        {
            // Width has changed
        }
        int heightWas = bottomWas - topWas; // Bottom exclusive, top inclusive
        if( v.getHeight() != heightWas )
        {
            // Height has changed
        }
    }
});

Another way (as dacwe answers) is to subclass your view and override onSizeChanged.