[原創]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等等。

 

 

  •  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM