自定义控件

来源:互联网 发布:淘宝联盟怎么一起结算 编辑:程序博客网 时间:2024/06/06 15:59

自定义控件:用系统自带的控件重新组合或者自定义类继承View(可以是View类,也可以是View的子类)或自定义类继承ViewGroup(可以是ViewGroup,也可以是其子类),实现特定的UI效果。

一.View的三个构造函数       

第一个构造函数:    当不需要使用xml声明或者不需要使用inflate动态加载时候,实现此构造函数即可  

第二个构造函数:    当需要在xml中声明此控件,则需要实现此构造函数。并且在构造函数中把自定义的属性与控件的数据成员连接起来。  

第三个构造函数:    接受一个style资源  

 

自定义控件构造方法参数AttributeSet attrs参数就是属性集合

 

在自定义控件中若我们没有使用自己规定的布局,而要展示内容,则需要我们自己去通过onDraw()画。Ondraw的重写方法中有参数canvas画笔,可以画文字和图片

当不使用时需要recycle()及时回收垃圾

 

如何在自定义控件中获取使用该自定义控件的时设置的属性

有三种获取属性的方法

在自定义控件的构造方法中

                   //获取属性的三种方式

                   //1.用命名空间获取

// attrs.getAttributeValue(namespace,name) // 我们自定义属性的namespace命名空间,name 属性名

                   Stringmy_name = attrs.getAttributeValue(

                   "http://schemas.android.com/apk/res/com.example.myattribute.attrs","my_name");

// 2.遍历属性集合// 在构造方法中     遍历出的是使用该view时设置的所有属性

                   for(int i = 0; i < attrs.getAttributeCount(); i++) {

                            System.out.println(attrs.getAttributeName(i)

                                               +attrs.getAttributeValue(i) + "\n");

                   }

// 3.使用系统工具获取属性可以获取所有引用该控件时设置的所有的属性

                   //第一个参数是AttributeSet属性参数,第二个是我们要获取的属性集合

                   //TypedArray array=context.obtainStyledAttributes(set, attrs)

                   TypedArrayarray = context.obtainStyledAttributes(attrs,

                                     R.styleable.MyAttributeView);

                   //同样需要遍历出已经设置的所有的属性

                   for(int i = 0; i < array.getIndexCount(); i++) {

                            intindex = array.getIndex(i);

                            switch(index) {

                            caseR.styleable.MyAttributeView_my_bg:

                                     Drawabledrawable=array.getDrawable(index);

                                     BitmapDrawabledrawables=(BitmapDrawable) drawable;

                                     bitmap=drawables.getBitmap();

                                     break;

                            caseR.styleable.MyAttributeView_my_size:

                                     size= array.getInt(index, 0);

                                     break;

                            caseR.styleable.MyAttributeView_my_name:

                                     name= array.getString(index);

                                     break;

                            }

                   }

主要使用的是方法三,这个可以通过查看View的构造方法知道,他的构造方法进入通过点击super

0 0
原创粉丝点击