Reputation: 4587
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?
Upvotes: 4
Views: 2228
Reputation: 8176
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);
}
}
Upvotes: 8