1. 程式人生 > >android自定義屬性attrs

android自定義屬性attrs

1.定義attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<declare-styleable name="MyView">
              <attr name="textColor" format="color" />  
              <attr name="textSize" format="dimension" />  
              <attr name="text" format="string" />
        </declare-styleable>  
</resources>

2.xml中使用自定義屬性
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:myandroid="http://schemas.android.com/apk/res/cn.com.androidtest"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"/>
    
    <cn.com.androidtest.ui.MyView
    	 android:layout_width="fill_parent" 
    	 android:layout_height="wrap_content" 
    	 myandroid:textColor="#ff0000"
    	 myandroid:textSize="20px"
    	 myandroid:text="http://wujiandong.iteye.com"/>
</LinearLayout>

3.命名規則

方式一:

    名稱空間寫法:xmlns:空間名="http://schemas.android.com/apk/res/自定義元件所在包名" 

             空間名隨便定義,引用時保持一致,如myandroid

方式二:

    名稱空間寫法:xmlns:空間名="http://schemas.android.com/apk/res-auto" 

             空間名隨便定義,引用時保持一致,如myandroid

    區別:

Solution:

Upgrade to latest SDK & ADT version (fixed was released since r17) and usehttp://schemas.android.com/apk/res-auto

 as custom attributes' namespace URI, see Revisions for ADT 17.0.0:

Added support for custom views with custom attributes in libraries. Layouts using custom attributes must use the namespace URI http://schemas.android.com/apk/res-auto instead of the URI that includes the app package name. This URI is replaced with the app specific one at build time.

如果你當前工程是做為lib使用,那麼你如上所寫 ,會出現找不到自定義屬性的錯誤 ,這時需要使用"http://schemas.android.com/apk/res-auto