標籤: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檔案中使用自訂屬性