详见《Android群英传》
3.6.2创建复合控件(本质是在讲如何自定义属性)
复合控件实质上是一个ViewGroup,通过自定义ViewGroup的子类来实现
其中关于自定义属性:
先在values下创建attrs资源文件,然后在styleable中声明自定义变量,变量名不应该与已有的重名
自定义类,并通过TypedArray类来获取自定义的属性值,赋给控件
在布局文件中指定命名空间,然后引入自定义控件,在其中通过命名空间来指定属性
此过程的本质是重写了传入属性的构造函数
代码如下
//在此构造函数中声明属性
public MyTopBar(Context context, AttributeSet attrs) {
//super中会将原生的属性从布局中获取,然后进行赋值
super(context, attrs);
setBackgroundColor(0xFFF59563);//设置topbar的属性
/*有个问题不太明白,如何将布局中赋的值映射到attrs.xml上自定义的属性上的*/
//将attrs中的自定义属性由布局中存储到TypedArray对象中,然后从该对象中获取值
TypedArray ta=context.obtainStyledAttributes(attrs,R.styleable.MyTopBar);//获取attrs.xml中的MyTopBar的自定义属性
mLeftTextColor=ta.getColor(R.styleable.MyTopBar_leftTextColor, 0);//第二个参数为缺省值
mLeftBackground=ta.getDrawable(R.styleable.MyTopBar_leftBackground);
mLeftText=ta.getString(R.styleable.MyTopBar_leftText);
mRightTextColor=ta.getColor(R.styleable.MyTopBar_rightTextColor, 0);
mRightBackground=ta.getDrawable(R.styleable.MyTopBar_rightBackground);
mRightText=ta.getString(R.styleable.MyTopBar_rightText);
mTitleTextColor=ta.getColor(R.styleable.MyTopBar_mtitleTextColor, 0);
mTitleTextSize=ta.getDimension(R.styleable.MyTopBar_mtitleTextSize, 10);
mTitle=ta.getString(R.styleable.MyTopBar_mtitle);
ta.recycle();//获取完TypedArray的值后,要调用recycle方法,回收
mLeftButton=new Button(context);
mRightButton=new Button(context);
mTitleView=new TextView(context);
//将获取到的值赋给相应的组件元素
mLeftButton.setTextColor(mLeftTextColor);
mLeftButton.setBackground(mLeftBackground);
mLe