将布局宽度与高度匹配

时间:2014-12-26 09:39:11

标签: android android-linearlayout

我有LinearLayout,我将宽度设置为match_parent。如何将高度与宽度匹配以获得正方形布局?

<LinearLayout
    android:id="@+id/linearLayout"
    android:orientation="horizontal"
    android:layout_margin="20dp"
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:gravity="center"
    android:background="@drawable/card_layout"> 
</LinearLayout>

4 个答案:

答案 0 :(得分:2)

要实现这一目标,您需要以编程方式获得@+id/linearLayout的宽度

LinearLayout mLinearLayout=(LinearLayout)findViewById(R.id.linearLayout);
int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels;
int screenHeight = mContext.getResources().getDisplayMetrics().widthPixels;

mLinearLayout.measure(screenWidth, screenHeight);
int layoutWidth = mLinearLayout.getMeasuredWidth();

然后将宽度值设置为高度

ViewGroup.LayoutParams params = mLinearLayout.getLayoutParams();
params.height = layoutWidth;
mLinearLayout.setLayoutParams(params);

您也可以像OnGlobalLayoutListener

中显示的@balaji koduri一样

答案 1 :(得分:0)

以编程方式执行 -

LinearLayout mLinearLayout=(LinearLayout)findViewById(R.id.linearLayout);
ViewGroup.LayoutParams params = mDialogLayout.getLayoutParams();
params.width = mContext.getResources().getDisplayMetrics().widthPixels;
params.height = mContext.getResources().getDisplayMetrics().widthPixels;

如果你想要其他尺寸 -

params.width = 200;
params.height = 200;

答案 2 :(得分:0)

试试这个:

final LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);

        layout.getViewTreeObserver().addOnGlobalLayoutListener(
                new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        LayoutParams params = (LayoutParams) layout
                                .getLayoutParams();
                        params.height = params.width;
                        layout.setLayoutParams(params);
                        layout.getViewTreeObserver().addOnGlobalLayoutListener(
                                null);
                    }
                });

答案 3 :(得分:0)

使用覆盖onMeasure

制作自定义布局
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}