Android layout檔案中 '?' 的作用
在Android layout檔案中,屬性引用資源一般使用@,例如
android:textColor="@color/white"
但在一些系統檔案中我們也可以看到有這樣的寫法
android:textColor="?android:color/textColor"
我們知道@是引用已經定義好的資源,如@color/white、@android:color/white,那 ‘?’ 呢?下面是文檔中的解釋
Referencing style attributes
A style attribute resource allows you to reference the value of an attribute in the currently-applied theme. Referencing a style attribute allows you to customize the look of UI elements by styling them to match standard variations supplied by the current theme, instead of supplying a hard-coded value. Referencing a style attribute essentially says, “use the style that is defined by this attribute, in the current theme.”
To reference a style attribute, the name syntax is almost identical to the normal resource format, but instead of the at-symbol (@), use a question-mark (?), and the resource type portion is optional. For instance:
?[:][/]
For example, here’s how you can reference an attribute to set the text color to match the “primary” text color of the system theme:
也就是說 ‘?’ 用來引用主題中的資源值,以顯示當前主題的風格類型。
一般設定主題有幾個方法,
在AndroidManifest中,application標籤裡,這樣會將主題應用到application下面所有的activity中
...
在AndroidManifest.xml中,activity標籤裡,這樣只給該activity設定主題
在Activity中代碼設定,需要在setContent()方法前調用
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(R.style.AppTheme); setContentView(R.layout.activity_main);}
例子:
主題style/AppTheme
主題style/AppTheme.Another
可以看到主題將所有view的background都設定為#ffff8800。原因是android:background是View的一個通用屬性,如果View自身沒有再去設定這個值的話,就會使用當前主題下的值。
如果我們只想改變某一個view的背景顏色怎麼辦?這裡就可以使用?這個符號。首先在attrs.xml中定義一個標籤
在主題中設定這個標籤的值
在布局中引用這個主題值
結果如下
如果我們再定義一些其他主題,如:
那麼只需要設定相應的主題就可以改變view的屬性值。
還可以再主題裡設定更多的標籤,這樣就可以完成像夜間主題這種背景、字型顏色等一系列屬性同時改變。