As the title states, I am trying to set the width of a layout element to be equal to the height (which is set to match the parent). I've tried setting the width parameter programatically from the height parameter, but this shows up as -1 rather than the actual height (since it matches the parent). Anyone know how I can create square layout elements whose size is dynamic? Thanks.
问题:
回答1:
So what I've been doing for things like this -- and I don't know that it's ideal, but it works quite well -- is use ViewTreeObserver.OnGlobalLayoutListener
. Something like this:
View myView = findViewById(R.id.myview);
ViewTreeObserver observer = myView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new SquareLayoutAdjuster());
class SquareLayoutAdjuster
implements ViewTreeObserver.OnGlobalLayoutListener {
@Override
public void onGlobalLayout() {
int dimension = myView.getHeight();
LayoutParams params = myView.getLayoutParams();
params.width = dimension;
myView.setLayoutParams(params);
observer.removeGlobalOnLayoutListener(this);
}
}
That's just the general idea, I don't know if it compiles as is, but basically in the onGlobalLayout()
method, your views are guaranteed to be measured. You remove the listener at the end to prevent it from being called multiple times (unless you need that to happen for whatever reason).
回答2:
the solution of KCOPPOCK works for me, thank you. But i got "java.lang.IllegalStateException: This ViewTreeObserver is not alive, call getViewTreeObserver() again" at runtime. So i use
findViewById(R.id.serie_main_layout).getViewTreeObserver().removeOnGlobalLayoutListener(this);
instead
observer.removeGlobalOnLayoutListener(this);
and all works perfectly.