如何在android style檔案中使用自訂屬性

來源:互聯網
上載者:User

標籤:exception   android   

      前幾天我在項目中遇到了這樣一個問題:我為項目編寫了一個自訂控制項,這個控制項會被大量複用,所以我準備在style.xml檔案中定義一個style來減少重複xml布局內容的編寫,但是裡面有一個自訂的控制項屬性,問題出現在這裡,雖然自訂屬性在layout布局xml中可以使用正常,但是卻無法在style中定義,本來這個控制項是大量服用的,style也是為了複用減少xml內容寫的,我可以把自訂屬性內容直接寫死在自訂控制項中,但是考慮到項目未來可能出現的變數,我還是準備將這個自訂屬性寫到style中,這樣即便有其他不同樣式的複用,我也只需再寫一個style即可。

在layout布局中使用自訂屬性是非常簡單,我們只需要在xml根節點xmlns:android="http://schemas.android.com/apk/res/android" 的後面加上我們自訂控制項的命名空間(栗子:xmlns:test="http://schemas.android.com/apk/res/packagename),然後就可以在自訂控制項節點裡自由使用自訂屬性了。

我在編寫style的時候,起初也以為style.xml也應該是這種使用方式,於是就在根節點添加了自訂控制項的命名空間,然後就在style中開始使用自訂屬性,如下:

<resources xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:test="http://schemas.android.com/res/com.zhufuing" >    <style name="test" >        <item name="test:name_text">hello,world!</item>           </style></resources>

但是這樣並不起作用,style.xml反而出現錯誤,報錯提示如下:

error: Error: No resource found that matches the given name: attr ‘test:name_text‘.

我在網上搜尋之後得到了正確的答案,其實我們在style.xml中使用自訂屬性的話,不需要寫自訂控制項的命名空間,我們只需要在style中使用命名控制項的地方換成自訂控制項的包名即可(注意:是包名,不帶自訂控制項的名字),如下:

<resources xmlns:android="http://schemas.android.com/apk/res/android" >    <style name="test" >        <item name="com.zhufuing:name_text">hello,world!</item>           </style></resources>

這樣就可以在style檔案中使用自訂屬性了。


參考連結:http://www.eoeandroid.com/forum.php?mod=viewthread&tid=316876

如何在android style檔案中使用自訂屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.