属性资源-1

本文介绍了如何在Android中创建自定义View属性资源。通过定义属性资源文件attrs.xml,开发者可以在自定义View组件中使用这些属性。文章详细展示了从定义属性到在自定义组件中应用属性的全过程。

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


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

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

  下面我们介绍如何自定义属性资源,并在自定义组件中使用自定义资源
1.首先在attrs.xml中定义属性资源
[html]  view plain  copy
 print ?
  1. <declare-styleable name="testView">  
  2.     <attr name="duration" format="integer"></attr>  
  3. </declare-styleable>  
  4. /resources>  
name=“testView"有什么作用呢,其实只有一个作用,在生成的R.java中有一个数组名:testView,如下:
[html]  view plain  copy
 print ?
  1. public static final class styleable {  
  2.   
  3.     public static final int[] testView = {  
  4.         0x7f010000  
  5.     };  
attr子元素的作用,在R.java的attr数组中生成一个项,如下:
[html]  view plain  copy
 print ?
  1. public final class R {  
  2.     public static final class attr {  
  3.    
  4.         public static final int duration=0x7f010000;  
  5.     }  
2. 在自定义View类里引用attrs文件里定义的属性为自己的属性设置值

[html]  view plain  copy
 print ?
  1. public dbView(Context context,AttributeSet attrs) {  
  2.     super(context, attrs);  
  3.     TypedArray typeArray=context.obtainStyledAttributes(attrs, R.styleable.testView);  
  4.     int duration=typeArray.getInt(R.styleable.testView_duration, 0);  
  5.     alphaDelta=255*SPEED/duration;  
  6. }  
 
3.使用自定义组件,并设置属性
[html]  view plain  copy
 print ?
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     xmlns:debai="http://schemas.android.com/apk/res/com.example.attrtest"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <TextView  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="@string/hello_world"  
  12.         tools:context=".MainActivity" />  
  13.     <com.example.attrtest.dbView   
  14.         android:layout_width="fill_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:src="@drawable/ee"  
  17.         debai:duration="60000"  
  18.         />  
  19. </LinearLayout>  
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值