Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime adjustment of layout parameters

Tags:

android

In a fragment's view, I'd like to adjust the layout params of one of the child views based on the width of the containing view, whose layout parameters are set to match_parent. What I need to do is to call getWidth/getHeight for the parent and then set the child view's ViewGroup.LayoutParameters, etc.

The problem is that getWidth will only return a valid value after the layout has been drawn the first time and I'm not sure if there are any fragment overrides that I can use for doing this. For example, the view's actual width is not determined when onCreateView or onStart are called.

So is there a straightforward way to implement this, or am I going to have to subclass a view and override onLayout or onMeasure?

like image 983
gordonwd Avatar asked Feb 22 '23 14:02

gordonwd


1 Answers

You could set a global layout listener on the view tree and do your diddling in there.

final ViewTreeObserver vto = myView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    public void onGlobalLayout() {
        // do layout tweaking based on measurements

        // remove the listener... or we'll be doing this a lot.
        vto.removeGlobalOnLayoutListener(this);
    }
}
like image 111
Brian Dupuis Avatar answered Mar 04 '23 18:03

Brian Dupuis