xml获取宽度并设置为android:height

时间:2013-12-07 07:04:01

标签: android xml width

<LinearLayout
 android:layout_width="match_parent"
 android:layout_height=" "
 android:orientation="vertical" >

这就是问题,假设我的LinearLayout宽度为match_parent,因此LinearLayout的宽度取决于设备的宽度。我不知道的是如何设置android:layout_height=" "值以对应android:layout_width="match_parent"的值,这样我就可以拥有 Square LinearLayout我知道我可以使用LayoutParams执行此操作,但有没有办法在xml上执行此操作?谢谢你们..

1 个答案:

答案 0 :(得分:1)

首先获得屏幕宽度

Display mDisplay = activity.getWindowManager().getDefaultDisplay();
int width  = mDisplay.getWidth();
int height = mDisplay.getHeight();

将尺寸设置为布局

LinearLayout layout = (LinearLayout)findViewById(R.id.LayoutID);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = width;
params.width = width;
layout.setLayoutParams(params);

在XML中:

<LinearLayout
 android:layout_width="0dp"
 android:layout_height="0dp"
 android:id="@+id/LayoutID"
 android:orientation="vertical" >