ScrollView 中 LinearLayout 的第一个子元素,具有设备高度的 1/3 space

First child of LinearLayout inside ScrollView with 1/3 space of device height

我有一个带有 LinearLayout 的 ScrollView,里面有 3 个元素。我希望第一个元素的高度为设备高度的 1/3,而另外 2 个元素的高度为 wrap_content,这是否可以在 xml 中执行,或者您将如何执行此操作?单独使用权重似乎是不可能的,因为 ScrollView 中的 LinearLayout 可能比设备的高度长。

你可以给第一个线性布局 weight=0.333 和 height=0 和其他两个布局 wrap_content

根据 Android 文档,android:layout_weight:

Indicates how much of the extra space in the LinearLayout is allocated to the view associated with these LayoutParams. Specify 0 if the view should not be stretched. Otherwise the extra pixels will be pro-rated among all views whose weight is greater than 0.

这意味着 weight 不依赖于屏幕高度,而仅依赖于其父视图,因此您无法从 xml 实现。为此,我将计算屏幕的高度,然后调整视图的大小:

Display screen = getWindowManager().getDefaultDisplay();
Point size = new Point();
screen.getSize(size);
int screenHeight = size.y;

myView.setLayoutParams(new LayoutParams(myView.getWidth(), screenHeight / 3));