我看到过一些例子使用android:layout_height="0px"或"0dip",但我不理解这样做的影响。似乎会使布局高度为0像素。这个值是否会被其他因素如“权重”或任何父视图的高度所限制?
我看到过一些例子使用android:layout_height="0px"或"0dip",但我不理解这样做的影响。似乎会使布局高度为0像素。这个值是否会被其他因素如“权重”或任何父视图的高度所限制?
你说得对,当你想让宽度或高度由权重控制时,将该值设置为0dip并让权重控制实际值是符合惯例的。尽管我很确定这里的0只是任意选择的,但你可以放置任何值,但放置0会使你的意图更清晰。
使用 LinearLayout 时,如果将 layout_weight
设置为非零值,并将 layout_height
(或 layout_width
)设置为 0px 或 0dip,则 LinearLayout 将根据权重在相应轴上分配任何未分配的空间。例如,如果查看下面的布局,id 为 *gestures_overlay* 的 View 具有 layout_height
0dip 和 layout_weight
1,因此父 LinearLayout 会将其拉伸以填充两个相邻 LinearLayout 之间的可用垂直空间。如果另一个视图具有相同的 0dip layout_height
和 layout_weight
值,则它们将根据权重值共享垂直空间。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="6dip"
android:text="@string/prompt_gesture_name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/gesture_name"
android:layout_width="0dip"
android:layout_weight="1.0"
android:layout_height="wrap_content"
android:maxLength="40"
android:singleLine="true" />
</LinearLayout>
<android.gesture.GestureOverlayView
android:id="@+id/gestures_overlay"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1.0"
android:gestureStrokeType="multiple" />
<LinearLayout
style="@android:style/ButtonBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/done"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="false"
android:onClick="addGesture"
android:text="@string/button_done" />
<Button
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="cancelGesture"
android:text="@string/button_discard" />
</LinearLayout>
</LinearLayout>
以下是官方开发者文档中的一个相关示例(http://developer.android.com/guide/topics/ui/layout/linear.html):
等分子视图
要创建一个线性布局,在屏幕上每个子视图使用相同的空间,请将每个视图的android:layout_height设置为"0dp"(对于垂直布局)或将每个视图的android:layout_width设置为"0dp"(对于水平布局)。然后将每个视图的android:layout_weight设置为"1"。
当我们需要在线性布局中为不同的视图分配相等的权重时, 则我们将分配layout/width = 0dp(对于水平方向)或layout/height = 0dp(对于垂直方向),并为该线性布局中的每个视图设置View/weight ==1。
优点:::: -- 将宽度或高度分配为0dp,则没有影响,由于weight==1,所有视图占用相同的空间并覆盖整个屏幕大小。
layout_width
或layout_height
设为0px
或0dip
更多是为了运行时的性能而非传统习惯。将其设为0px
(或0dip
)可以跳过初始化所需的 CPU 循环,视图的宽度/高度会根据需要进行调整。简而言之,运行时只需要计算一次高度/宽度,而不是两次... - Mahendra Liya