自定义控件属性补充、9patch图

来源:互联网 发布:linux安装包放在哪里 编辑:程序博客网 时间:2024/06/05 19:28

自定义控件属性和自定义控件类关联时,在两个参数的构造方法中,除了通过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) {// 当前状态为开,则令左边起始位置为0slide_left = back.getWidth() - slide.getWidth();} else {// 当前状态为关,则令左边起始位置为差slide_left = 0;}// 初始化时,刷新当前状态invalidate();break;}}initView();}

该方法在获得属性实例时,不用每次都写命名空间,方便了一些。

在上面代码中自定义开关的图片资源在获得属性实例时就赋值了,所以,在initView()方法中就不用再赋值了。

9patch图

左边和上边代表可以拉伸的区域。

右边和下边代表可以放置其他控件的区域。

0 0
原创粉丝点击