2013-05-28 153 views
0

我已經爲TextView的contentBg風格定義了紅色。我是否可以通過更改或重命名父級樣式中的樣式名稱myContentNew將TextView顏色更改爲藍色? TextView樣式name-contentBG不應該改變。在Android系統中可能嗎?繼承Android風格

<RelativeLayout 
    style="@style/myContent" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"> 
<TextView 
    style="@style/contentBG" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"/> 
</RelativeLayout> 

我的代碼應該像下面

<RelativeLayout 
     style="@style/myContentNew" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"> 
    <TextView 
     style="@style/contentBG" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"/> 
</RelativeLayout> 

你可以得到明確的想法與我的附加的圖像。 enter image description here

像CSS:

.myContent .contentBg{background-color:red} 
.myContentNew .contentBg{background-color:blue} 

感謝

+0

似乎你試着建立一個主題吧?你需要在一種佈局還是所有佈局中做到這一點? –

+0

其實我想用這個作爲主動或非主動狀態與上述要求 –

+0

我不認爲你可以直接設置這種類型的繼承。我看到的唯一方法是設置2個主題並使用樣式作爲引用,這些引用將根據所選主題進行更改。 –

回答

1

恐怕不行。

一旦設置contentBG風格。它不能改變,但在代碼中。

1

下面是創建2個不同主題的例子:

您需要先修改清單文件來調用默認的自定義主題,例如:

<application 
    android:name="RateDayApplication" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/CustomTheme" > 

然後,在你的風格.xml文件,準備2個不同的主題,含有相同的風格contentBG

<!-- *** THEME WITH RED BG*** --> 
<style name="CustomTheme" parent="@android:style/Theme.Holo.Light"> 
    <item name="contentBG">@style/contentBGred</item> 

</style> 

<style name="contentBGred" > 
    <item name="android:colorBackground">@color/red</item> 
</style> 

<!-- *** THEME WITH BLUE BG*** --> 
<style name="CustomThemeNew" parent="@android:style/Theme.Holo.Light"> 
    <item name="contentBG">@style/contentBGblue</item> 
</style> 

<style name="contentBGblue" > 
    <item name="android:colorBackground">@color/blue</item> 
</style> 

重要:這裏我使用Theme.Holo.Light作爲父主題,如果您使用不同的主題,則可以更改它。

在上面的兩個主題中,風格具有相同的名稱,它將用作XML文件中的參考。爲了聲明此參考,您必須將其添加到您的values文件夾下的無標題attrs.xml的文件中。

以下是內容:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <attr name="contentBG" format="reference" /> 
</resources> 

一旦完成,你只需要調用這種風格這種方式在你的XML文件(你不需要在佈局風格了):

<RelativeLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"> 
<TextView 
    style="?contentBG" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"/> 
</RelativeLayout> 

這裏的問號表示將使用參考加載樣式。將使用的風格將是Activity上應用的當前主題之一。

您可以輕鬆地設置您想使用這種方式的活動主題是:

setTheme(R.style.CustomTheme); 

setTheme(R.style.CustomThemeNew);