How to set size and layout in onSizeChanged?

JOG picture JOG · Jun 7, 2011 · Viewed 17.1k times · Source

I can't get my elements, for example ListView, to resize properly.

I got a ListActivity for searching, with a dashboard, an editbox and a listview. The idea is to hide the actionbar while the keyboard is showing.

I extended LinearLayout, to listen to view size changes (as recommended here) :

public class SizeChangingLinearLayout extends LinearLayout {
    //...
    @Override
    protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld)
    {        
        View actionbar = mainView.findViewById(R.id.actionbar);

        if (yNew > yOld) 
            actionbar.setVisibility(View.VISIBLE);
        else if (yNew < yOld) 
            actionbar.setVisibility(View.GONE);

        super.onSizeChanged(xNew, yNew, xOld, yOld);

    }
}

The hiding/showing of the actionbar works as expected but there is a gap below the ListView of the same height as the hidden actionbar. As soon as any graphics change (e.g. writing in the editbox) the ListView fills the gap. A similar behavior appears in reverse, when hiding the keyboard.

enter image description here

[Edit]

The same problem also appears in changing other layout. Changing Visibility of things in onSizeChanged shows directly, but changing sizes and margins does not show until some other user action redraws those views. Invalidation does not work from onSizeChanged.

[/Edit]

I have tried to refresh the graphics by:

  • invalidate-ing both the custom LinearLayout and the ListView (as recommended here)
  • notifyDataSetChanged on the list's adapter
  • forceLayout

... and more, without success. Why is the ListView not resizing at first? Do I have to override onLayout in my extended LinearLayout? What have I missed?

Answer

aspartame picture aspartame · Jun 21, 2011

Adding the following at the end of onSizeChanged() will solve it:

Handler handler = new Handler();
handler.post(new Runnable() {

    @Override
    public void run() {
        requestLayout();
    }
});

See the answer to this question: Views inside a custom ViewGroup not rendering after a size change