Android layout檔案中 '?' 的作用

來源:互聯網
上載者:User

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的屬性值。
還可以再主題裡設定更多的標籤,這樣就可以完成像夜間主題這種背景、字型顏色等一系列屬性同時改變。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.