创建动态大小的正方形(等于高度和宽度)的Andr​​oid UI元素正方形、宽度、元素、高度

2023-09-08 08:49:49 作者:糟糕血溅

正如标题状态,我试图设置一个布局元素的宽度是相等的高度(其被设置为相匹配的父)。我试着从高度参数编程设置宽度参数,但是显示为-1,而不是实际身高(因为它的父匹配)。任何人都知道我可以创建多布局元素的大小是动态的?谢谢你。

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.

推荐答案

所以,我一直在做这样的事情 - 我不知道这是理想的,但它工作得很好 - 是用 ViewTreeObserver.OnGlobalLayoutListener 。事情是这样的:

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);
    }
}

这只是一般的想法,我不知道,如果它编译原样,但基本上在 onGlobalLayout()方法,你的观点是保证测量。你到底要prevent它被调用多次删除侦听器(除非你需要这样的事情发生无论何种原因)。

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).