Android动态更改布局大小

时间:2016-06-01 04:58:18

标签: android android-framelayout

我想要一个正方形FrameLayout来填充它的父级宽度,其高度与它的宽度相匹配。我已尝试在布局中添加 addOnLayoutChangeListener ,但我无法从内部调用requestLayout,因此我无法告诉它调整大小。

我可以做些什么来使它的高度等于它在运行时的宽度?

2 个答案:

答案 0 :(得分:1)

简单的解决方案是扩展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>

答案 1 :(得分:0)

获取视图后,请执行以下操作

    ViewGroup.LayoutParams lp = view.getLayoutParams();
    Display display = ((AppCompatActivity) context).getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int screenWidth = size.X;
    lp.height = screenWidth;
    view.setLayoutParams(lp);