自定义控件属性和自定义控件类关联时,在两个参数的构造方法中,除了通过attrs.getAttributeValue(命名空间,属性名);方法获得属性的实例外,还可以用
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.myToggleBtn);方法。
具体操作如下:
public myToggleButton(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.myToggleBtn);
int count = ta.getIndexCount();
for (int i = 0; i < count; i++) {
// 获得某个属性的id值
int itemId = ta.getIndex(i);
switch (itemId) {
case R.styleable.myToggleBtn_myBackground:
backId = ta.getResourceId(itemId, -1);
if(backId == -1){
throw new RuntimeException("请设置背景图片");
}
back = BitmapFactory.decodeResource(getResources(), backId);
break;
case R.styleable.myToggleBtn_mySlideBtn:
slideId = ta.getResourceId(itemId, -1);
if(slideId == -1){
throw new RuntimeException("请设置滑动图片");
}
slide = BitmapFactory.decodeResource(getResources(), slideId);
break;
case R.styleable.myToggleBtn_currentState:
currStat = ta.getBoolean(itemId, false);
if (currStat) {
// 当前状态为开,则令左边起始位置为0
slide_left = back.getWidth() - slide.getWidth();
} else {
// 当前状态为关,则令左边起始位置为差
slide_left = 0;
}
// 初始化时,刷新当前状态
invalidate();
break;
}
}
initView();
}该方法在获得属性实例时,不用每次都写命名空间,方便了一些。
在上面代码中自定义开关的图片资源在获得属性实例时就赋值了,所以,在initView()方法中就不用再赋值了。
9patch图
左边和上边代表可以拉伸的区域。
右边和下边代表可以放置其他控件的区域。
本文介绍如何使用TypedArray简化自定义控件属性获取过程,并通过示例代码展示了如何为自定义切换按钮设置背景和滑动图片资源。

被折叠的 条评论
为什么被折叠?



