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

    区别:

Issue 9656: Library projects don't support custom XML attributes for custom classes

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值