【總結(jié)】android中style的繼承關(guān)系

這兩天整理之前的代碼時(shí),發(fā)現(xiàn)一個(gè)蠻有意思的小細(xì)節(jié),項(xiàng)目中的style竟然存在多繼承的寫(xiě)法。
就是一個(gè)style既存在前綴繼承的寫(xiě)法,同時(shí)還有通過(guò)parent繼承,就像這樣

    <style name="A.B" parent="C">
        <item ...>
    </style>

其實(shí)有一點(diǎn)懵逼的,雖然我的理性告訴我,style單繼承,parent優(yōu)先級(jí)比較高,但是還是覺(jué)得需要驗(yàn)證一下才比較放心。
驗(yàn)證這個(gè)繼承方式比較簡(jiǎn)單,甚至不用編譯代碼,用AS的預(yù)覽模式就可以。

我用TextView進(jìn)行演示,我們先有四個(gè)style,前兩個(gè)為父類,后兩個(gè)為子類

 
    <style name="Red20Text">
        <item name="android:textColor">#FF0000</item>
        <item name="android:textSize">20dp</item>
    </style>

    <style name="BlueBlodText">
        <item name="android:textColor">#0000FF</item>
        <item name="android:textStyle">bold</item>
    </style>

    <style name="Red20Text.BothText" parent="BlueBlodText">
    </style>

    <style name="Red20Text.GreenBothText" parent="BlueBlodText">
        <item name="android:textColor">#00FF00</item>
    </style>

然后寫(xiě)幾個(gè)TextView分別使用這幾個(gè)style

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="默認(rèn)文字" />

    <TextView
        style="@style/Red20Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="20號(hào)紅色" />

    <TextView
        style="@style/BlueBlodText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="藍(lán)色加粗" />

    <TextView
        style="@style/Red20Text.BothText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="繼承兩個(gè)" />

    <TextView
        style="@style/Red20Text.GreenBothText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="繼承兩個(gè)并重寫(xiě)一個(gè)屬性" />
style的繼承.png

從預(yù)覽中就可以看到,使用Red20Text.BothText的TextView(第四個(gè))繼承了parent父類的加粗以及藍(lán)色屬性,但是沒(méi)有繼承前綴父類的任何屬性,所以,同時(shí)繼承兩個(gè)style的時(shí)候,只有parent方式的屬性得到了繼承,前綴方式的屬性不會(huì)被繼承,此時(shí)只是作為一個(gè)名字存在。當(dāng)子類父類存在相同屬性時(shí),父類屬性會(huì)被子類屬性覆蓋掉,類似于java的繼承。

結(jié)論:style為單繼承,parent方式優(yōu)先級(jí)高于前綴繼承,同時(shí)存在時(shí),前綴的作用只作為名字

雖然這個(gè)寫(xiě)法沒(méi)什么問(wèn)題,google官方代碼也都會(huì)這么寫(xiě),比如在預(yù)定義的values文件夾下面,會(huì)看到好多類似于

    <style name="Theme.AppCompat.Light" parent="Base.Theme.AppCompat.Light"/>
    <style name="Theme.AppCompat.Light.DarkActionBar" parent="Base.Theme.AppCompat.Light.DarkActionBar"/>

的style,但是我還是把項(xiàng)目里存在的這種寫(xiě)法全部刪掉了,大概因?yàn)槲覒邪?,懶得每次都想到底怎么生效?br> ...(* ̄0 ̄)ノ


個(gè)人理解,難免有錯(cuò)誤紕漏,歡迎指正。轉(zhuǎn)載請(qǐng)注明出處。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容