標籤:
在Android的xml布局檔案裡,xmlns:android="http://schemas.android.com/apk/res/android",就是定義了xml的命名空間,以android開頭,比如:android:id="@+id/i_am"
有時候,我們也想自訂命名空間。比如,在xmlns:android="http://schemas.android.com/apk/res/android"的下面寫上:xmlns:app="http://schemas.android.com/apk/res-auto"。以後就可以在整個xml布局檔案裡的控制項下面設定屬性,例如:app:me="@drawable/is_me"。但是,這個屬性必須在res/values/attrs.xml裡面聲明過:
1 <declare-styleable name="isme">2 <attr name="me" format="reference" />3 </declare-styleable>
屬性設定好了,但是怎麼在java代碼裡面擷取到這些控制項的屬性呢。
1 public CustomComponent(Context context, AttributeSet attrs) { 2 super(context, attrs); 3 4 TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CusComponent); 5 6 int imageSrcId; 7 8 try { 9 imageSrcId = a.getResourceId(R.styleable.isme_me,R.drawable.myimage);10 11 } finally {12 a.recycle();13 }14 LayoutInflater inflater = LayoutInflater.from(context);15 16 inflater.inflate(R.layout.custom_component_layout, this, true); // 給自訂控制項設定布局17 b = (ImageButton)findViewById(R.id.btn); // 擷取到布局上的ImageButton18 b.setImageResource(imageSrcId);19 20 }
還有一點,就是命名空間的問題,就是res與res-auto的區別。通常我們在布局檔案中使用自訂屬性的時候 會這樣寫 xmlns:app=http://schemas.android.com/apk/res-auto,但如果你當前工程是做為lib使用,那麼你如上所寫 ,會出現找不到自訂屬性的錯誤 。 這時候你就必須 寫成 xmlns:app=http://schemas.android.com/apk/res/包名路徑。
如果自訂屬性出現報錯的話,例如這樣的錯誤:Unexpected namespace prefix "app" found for tag fragment。解決方案:
到Eclipse的problems 標籤找到這個錯誤,右鍵然後選擇quick fix菜單,在彈出的菜單中選擇不檢查這個檔案(Disable check in this file only)就可以了。
之前看了別人這麼多的文章,而自己又很懶,沒寫過文章。所以,這一次碰到了自訂屬性的配置問題,所以就把自己碰到的問題以及解決方案write下來,以供參考。第一次寫,勿噴。
Android自訂控制項的屬性配置