【问题标题】:What is the trick with 0dip layout_height or layouth_width?0dip layout_height 或 layouth_width 的诀窍是什么?
【发布时间】:2011-11-05 10:21:08
【问题描述】:

我的意思是为什么有人希望他们看到 0dip 高度? 这个我看过很多次了,肯定有什么诡计,但我不明白。

        <TextView android:gravity="top" android:textColor="#FFFF0000"
            android:textSize="20dip" android:text="TextView"
            android:layout_height="0dip" android:layout_width="fill_parent"
            android:id="@+id/contactName"></TextView>

为什么他们不使用例如 wrap_content ?他们想要达到什么目标?

【问题讨论】:

    标签: android layout height


    【解决方案1】:

    这主要用于带有LinearLayout 的视图。 LinearLayout 知道三个“布局”属性:

    1. android:layout_height
    2. android:layout_width
    3. android:layout_weight

    您可以在tutorial project 中找到带有android:layout_weight 的示例。

    所以当android:layout_weight 用于View X 并且LinearLayout 是水平的时,X 的android:layout_width 将被简单地忽略。

    类似地,当android:layout_weight 用于View X 并且LinearLayout 是垂直的,那么X 的android:layout_height 将被忽略。

    这实际上意味着,您可以在那些被忽略的字段中输入任何内容:0dpfill_parentwrap_content。没关系。但建议使用0dp,因此View 不会对其高度或宽度进行额外计算(然后将其忽略)。这个小技巧只是节省了 CPU 周期。

    【讨论】:

    • 这是不正确的。尝试使用不同的权重(例如 1,2,3)并查看使用 match_parent 和 0px(或 0dp)之间存在差异
    • @androiddeveloper,你能详细说明一下吗?为什么会这样?如果可能,您能否链接到有关该主题的文档/其他参考资料?
    • @batbrat 我不记得我在哪里读到过这个。但是,您可以尝试一下,然后自己看看。您还可以阅读 Lint 对此的建议,因为它不利于 LinearLayout 的性能。
    • @androiddeveloper,我希望得到一个官方的说法,而不是实验验证基于 0dp 与 match_parent 等的布局变化。我知道使用非零值会导致额外的计算出于性能原因,最好避免这种情况。感谢您的快速回复。
    • @batbrat 抱歉。我只是不记得了。也许我什至没有读过它,只是注意到它。
    【解决方案2】:

    这通常用于在一个线性布局中有很多视图并且设置了 android:layout_weight="1" 以便两个视图占据相等的空间。例如:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:text="TextView" />
    
        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:text="TextView" />
    
    </LinearLayout>
    

    在这种情况下,视图将采用与所有其他视图一样高的高度。

    【讨论】:

    • 是的,在这种情况下,我通常设置 0dip 宽度或高度。或者您可以使用它来隐藏小部件,但是在这种情况下应该使用可见性属性。
    【解决方案3】:

    android:layout_height="0dp" 用于各种代码,因为:

    1. 这意味着以后可以根据其他布局限制更改视图的高度。
    2. 这是一种常见的做法,经常出现在相对和线性布局中。

    例如:

    android:layout_height = "0dp"
    android:layout_weight = "1.0"
    

    设置为“0dp”时的高度或宽度,主要与“重量”结合使用。例如你想填充所有可用的高度空间然后使用上面的代码和同样的宽度情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多