2016-10-03 122 views
5

我有我的styles.xml一些自定義主題,現在
每當活動發生的主題,它採用了colorPrimarycolorPrimaryDarkcolorAccent值。
對於我的佈局背景,我使用的是?attr/colorAccent,因此它可以根據所選主題選擇背景顏色。
如果我使用任何上述值,它工作正常。但我想爲我的背景顏色定義一個自定義項目值。
我嘗試了這樣的下面,但它沒有奏效。任何想法,使其工作?
我的自定義主題自定義值:
如何在android主題聲明中添加自定義項目?

<style name = "customTheme" parent="Theme.AppCompat.Light.NoActionBar"> 
    <item name="colorPrimary">#4285f4</item> 
    <item name="colorPrimaryDark">#2C75F2</item> 
    <item name="colorAccent">#E1FFC7</item> 
    <item name="customBgColor">#d3d3d3</item> 
</style> 


我想用它在佈局的風格

<style name="layoutStyle" > 
    <item name="android:background">?attr/customBgColor</item> 
</style> 

回答

11

創建圖像所示的attars.xml文件。

<?xml version="1.0" encoding="utf-8"?> 
<resources> 

    <!-- Other values--> 
    <attr name="customBgColor" format="reference" /> 

</resources> 

enter image description here

customTheme 1

<style name = "customTheme1" parent="Theme.AppCompat.Light.NoActionBar"> 
    <!-- Other values--> 
    <item name="customBgColor">#d3d3d3</item> 
</style> 

customTheme 2

<style name = "customTheme2" parent="Theme.AppCompat.Light.NoActionBar"> 
    <!-- Other values--> 
    <!-- Black Color in theme2--> 
    <item name="customBgColor">#111111</item> 
</style> 

設置顏色來作爲TextView EXA mple。

您可以在任何地方的任何小部件以類似的方式使用它。

TextView用於以下活動。

<TextView 
    android:id="@+id/txt_rate_us_about" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:text="Rate us on Play Store!" 
    android:textColor="?attr/customBgColor" 
    android:textSize="20dp" /> 

想要動態設置主題。

public class AboutUsActivity extends Activity { 

    int theme = 1; 
    // int theme = 2; 2nd theme. 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     switch (theme) { 
      default: 
      case 1: 
       this.setTheme(R.style.customTheme1); 
       break; 
      case 2: 
       this.setTheme(R.style.customTheme2); 
       break; 

     } 
     // you must call `setTheme()` before `setContentView()` 
     setContentView(R.layout.activity_about); 

    } 

對於多個活動,您分別爲每個活動設置主題。

+0

我錯過了定義屬性,添加attrs.xml後,它工作正常。謝謝@sohail。 – Shree

+0

而不是將顏色代碼放入物品中。把它放在color.xml中,並將該顏色標籤添加到項目中.. – gayan1991

相關問題