我想要一个正方形的FrameLayout来填充其父元素的宽度,并且其高度与它的宽度匹配。我尝试将addOnLayoutChangeListener添加到布局中,但是我不能从内部对其调用requestLayout,所以我无法告诉它调整大小。

在运行时如何使其高度等于宽度?

最佳答案

简单的解决方案是扩展FrameLayout

public class SquareFrameLayout extends FrameLayout {

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
            // or you can use this if you want the square to use width as it basis
             super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }
}


使用它如下所示的布局

 <your.package.SquareFrameLayout
   android:layout_width="match_parent"
    ......>
        <!-- other child views -->
 </your.package.SquareFrameLayout>

08-04 15:29