Android 自定义View(二) 自定义属性

给自定义的View(这类View一般直接或间接继承ViewGroup这类,当然继承普通的View也可以自定义属性,比如画一个圆,需要的大小和圆心,画一张位图的引用等等),添加一些属性,那么就需要在/value下创建一个attr.xml资源文件

name="TopBar">
    name="title" format="string" />
    name="titleTextSize" format="dimension" />
    name="titleTextColor" format="color" />
    name="leftTextColor" format="color" />
    name="leftBackground" format="reference|color" />
    name="leftText" format="string" />
    name="rightTextColor" format="color" />
    name="rightBackground" format="reference|color" />
    name="rightText" format="string" />
 
  

中的format属性类型:string ,color ,reference(引用),dimension(尺寸值Dip等),boolean,float,integer,enum...

 

定义的时候

 
                    
                           
                           
                               
 

使用的时候

 
                   xmlns:android = "http://schemas.android.com/apk/res/android" 
                    android:orientation = "vertical" 
                    android:layout_width = "fill_parent" 
                    android:layout_height = "fill_parent" /> 


如何使用这些自定义属性呢~

// 通过这个方法,将你在atts.xml中定义的declare-styleable
// 的所有属性的值存储到TypedArray中
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.TopBar);
接着使用     ta.getXXX();方法获得获得属性  getString(),getDimension(),getColor(),getDrawable().......
String mRightText = ta.getString(R.styleable.TopBar_rightText);
当取完资源的时候一般要调用
ta.recycle();   //避免重复创建

接着就可以实例化这个ViewGroup中的组件Button Image这类的,在紧接着
new LayoutParams(
        LayoutParams.WRAP_CONTENT,
        LayoutParams.MATCH_PARENT);
mTitlepParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
addView(mTitleView, mTitlepParams);
有时候还需要为按钮,图片设置点击事件,设计一个接口,自定义View开一个公共方法,调用这个接口方法,交给子类去实践接口方法


自定义View注重onDraw()

ViewGroup注重布局OnLayout(),单也不是所有的ViewGroup都需要这些自定义属性

你可能感兴趣的:(Android 自定义View(二) 自定义属性)