What is the trick with 0dip layout_height or layou

2019-01-14 07:05发布

I mean why anybody want they view to be 0dip height ? I have seen this many times, there must be some kind of trick, but I do not get it.

        <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>

Why they don't use for example wrap_content ? what do they want to achieve ?

3条回答
Anthone
2楼-- · 2019-01-14 07:37

This is usually used when having many views inside a linearlayout and have set android:layout_weight="1" in order both views to take equal space. for example:

<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>

In that case, the view will take as much height as all other views.

查看更多
时光不老,我们不散
3楼-- · 2019-01-14 07:41

This is heavily used for views withing LinearLayout. There are three "layout" attributes that LinearLayout is aware of:

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

You can find example with android:layout_weight in tutorial project.

So when android:layout_weight is used on View X and LinearLayout is horizontal, then X's android:layout_width is simply ignored.

Similar, when android:layout_weight is used on View X and LinearLayout is vertical, then X's android:layout_height is ignored.

This actually means, that you can put anything in those ignored fields: 0dp or fill_parent or wrap_content. It doesn't matter. But it's recommended to use 0dp so View's do not do extra calculation of their height or width (which is then ignored). This small trick simply saves CPU cycles.

查看更多
老娘就宠你
4楼-- · 2019-01-14 07:46

The android:layout_height="0dp" is used in various codes because:

  1. It means the height of the view can be changed later due to other layout constraints.
  2. It is a common practice and often seen in relative and linear layouts.

e.g:

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

Height or width when set to "0dp", are mostly used in combination with "weight". e.g. you want to fill all the available space for height then use the above code and like wise the same case for width.

查看更多
登录 后发表回答