Android属性资源

    在XML布局文件中使用Android系统提供的View组件时,开发者可以指定多个属性,这些属性可以控制View组件的外观。我们也可以开发自己的View组件,同时也可以给自定义组件指定自定义属性,这就是所谓的属性资源,一般属性资源放在attrs.xml或者以attrs为开头的xml文件中。


    属性资源资源文件存放在res/values目录下,属性资源文件的根元素是<resources.../>,该元素里面包含两个子元素:

  • attr:定义一个属性
  • declare-styleable:定义一个styleable对象,每个styleable对象就是一组attr属性的集合。

  下面我们介绍如何自定义属性资源,并在自定义组件中使用自定义资源
1.首先在attrs.xml中定义属性资源
    <declare-styleable name="testView">
        <attr name="duration" format="integer"></attr>
    </declare-styleable>
</resources>
name=“testView"有什么作用呢,其实只有一个作用,在生成的R.java中有一个数组名:testView,如下:
    public static final class styleable {

        public static final int[] testView = {
            0x7f010000
        };
attr子元素的作用,在R.java的attr数组中生成一个项,如下:
public final class R {
    public static final class attr {
 
        public static final int duration=0x7f010000;
    }
2. 在自定义View类里引用attrs文件里定义的属性为自己的属性设置值

	public dbView(Context context,AttributeSet attrs) {
		super(context, attrs);
		TypedArray typeArray=context.obtainStyledAttributes(attrs, R.styleable.testView);
		int duration=typeArray.getInt(R.styleable.testView_duration, 0);
		alphaDelta=255*SPEED/duration;
	}
 
3.使用自定义组件,并设置属性
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:debai="http://schemas.android.com/apk/res/com.example.attrtest"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />
   	<com.example.attrtest.dbView 
   	    android:layout_width="fill_parent"
   	 	android:layout_height="wrap_content"
   	 	android:src="@drawable/ee"
   	 	debai:duration="60000"
   	    />
</LinearLayout>
 

注意:属性一旦定义完毕,任何组件都可以使用

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值