自定义控件的属性定义和使用

有时候为了完成某些功能,需要组合一些系统控件,为了以后使用方便,就可以把这个功能独立成一个单独的控件,里面用到的一些参数可以设置控件的属性,在xml中进行设置,步骤如下:

1、建立一个自定义控件 ExtendsView extends View 

2、在values 文件下定义一个attrs.xml 文件

1 <?xml version="1.0" encoding="utf-8"?>  
2 <resources>  
3     <declare-styleable name="ExtendsView">  
4         <attr name="myattr" format="boolean" />  
5     </declare-styleable>  
6 </resources>  

3、在自定义控件的构造函数里得到该属性值

 1 public ExtendsView(Context context,AttributeSet attrs)  
 2     {  
 3         super(context,attrs);  
 4    
 5         TypedArray a = context.obtainStyledAttributes(attrs,  
 6                 R.styleable.ExtendsView);  
 7           
 8         boolean myattr = a.getColor(R.styleable.ExtendsView_myattr,  
 9                 false);  
10  
11         a.recycle();  
12     }  

 4、xml中使用,根布局添加 xmlns:app="http://schemas.android.com/apk/res-auto"

<View app:myattr="true" />

 

posted @ 2016-06-05 14:32  Xiao.T  阅读(309)  评论(0编辑  收藏  举报