在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); // 獲取到布局上的ImageButton 18 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下來,以供參考。第一次寫,勿噴。