Android中的android:layout_width和android:width的區(qū)別

在android系統(tǒng)中,我們可以通過在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在內(nèi)的所有View均可以在layout文件中指定布局參數(shù)。
1.先說android:layout_width/android:layout_height
(1)每一個View必須要定義的兩個屬性是layout_width和layout_height,這兩個屬性的值只能在"match_parent"、"wrap_content"、"fill_parent"之間選擇一種。注意,match_parent和fill_parent實際上是一樣的,可以在ViewGroup的內(nèi)部類LayoutParams中找到定義,其值均為-1(說明:布局文件等xml文件在程序運行時會被解析成對應(yīng)的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的寬高值將會按照包裹自身內(nèi)容的方式來確定。

(2)android:layout_width/android:layout_height兩種屬性還可以指定具體的寬高,此時的view的大小在一般情況下就是這兩種屬性指定的精確大小,如果此view的父view過小,那么這個view可能顯示不全。

(3)在LinearLayout控件中,android:layout_width/android:layout_height還可以和android:layout_weight一同使用,其中l(wèi)ayout_weight標識此view所占的空間比例,通常我們將layout_weight設(shè)置為大于0的數(shù)值,并將(android:layout_width或android:layout_height)設(shè)置為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兩者設(shè)置尺寸值大小,如16dp,60px等等。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容