[原创]Android中的android:layout_width和android:width的区别

在android系统中,我们可以通过在xml资源文件中定义布局,一般的写法是:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffffff"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

包括自定义view在内的所有View均可以在layout文件中指定布局参数。

1.先说android:layout_width/android:layout_height 

(1)每一个View必须要定义的两个属性是layout_width和layout_height,这两个属性的值只能在"match_parent"、"wrap_content"、"fill_parent"之间选择一种。注意,match_parent和fill_parent实际上是一样的,可以在ViewGroup的内部类LayoutParams中找到定义,其值均为-1(说明:布局文件等xml文件在程序运行时会被解析成对应的java对象)

      /**
         * Special value for the height or width requested by a View.
         * FILL_PARENT means that the view wants to be as big as its parent,
         * minus the parent's padding, if any. This value is deprecated
         * starting in API Level 8 and replaced by {@link #MATCH_PARENT}.
         */
        @SuppressWarnings({"UnusedDeclaration"})
        @Deprecated
        public static final int FILL_PARENT = -1;

        /**
         * Special value for the height or width requested by a View.
         * MATCH_PARENT means that the view wants to be as big as its parent,
         * minus the parent's padding, if any. Introduced in API Level 8.
         */
        public static final int MATCH_PARENT = -1;

        /**
         * Special value for the height or width requested by a View.
         * WRAP_CONTENT means that the view wants to be just large enough to fit
         * its own internal content, taking its own padding into account.
         */
        public static final int WRAP_CONTENT = -2;

FILL_PARENT / MATCH_PARENT / WRAP_CONTENT代表此view在父view中长宽的“确定方式”,这种确定方式会直接影响此view在measure时确定自己的大小。FILL_PARENT / MATCH_PARENT这两种方式代表此view的宽(或者高)将会和父控件的宽高相等,WRAP_CONTENT这种方式代表此view的宽高值将会按照包裹自身内容的方式来确定。

(2)android:layout_width/android:layout_height两种属性还可以指定具体的宽高,此时的view的大小在一般情况下就是这两种属性指定的精确大小,如果此view的父view过小,那么这个view可能显示不全。

(3)在LinearLayout控件中,android:layout_width/android:layout_height还可以和android:layout_weight一同使用,其中layout_weight标识此view所占的空间比例,通常我们将layout_weight设置为大于0的数值,并将(android:layout_width或android:layout_height)设置为0。LinearLayout的orientation如果是水平方向,那么layout_weight指水平方向的比例大小,竖直方向同理。

2.再说android:width/android:height

不是所有的view都具有android:width/android:height这两种属性,且即便具有这两种属性,也不必声明。这两个属性一般用来控制view的精确大小,如64dp,1px等,在TextView等控件中可以找到此属性,但是一般情况下是不会使用这两个属性的。在给view定义精确大小时,采用的方式是给android:layout_width/android:layout_height两者设置尺寸值大小,如16dp,60px等等。

 

 

  •  

 

posted @ 2012-07-03 23:21  carbs  阅读(76952)  评论(0编辑  收藏  举报