自定义组件的属性
步骤如下
【1】在Values资源文件下新建myview.xml
<resources>
<declare-styleable name="myview">
<attr name="myview_background" format="reference"/>
<attr name="myview_paintwidth" format="reference|dimension"/>
</declare-styleable>
</resources>
自定义两个属性背景图、画笔笔触大小;
【2】在布局文件中使用自定义属性
首先引入然后使用
【3】在Java文件中获取自定义组件信息
我们知道在在自定义组件Java文件中,的构造函数
public MyBitmapView2(Context context, AttributeSet attrs){}
attrs就是用来解析XML文件的
解析代码
public MyBitmapView2(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.myview);
BitmapDrawable dra = (BitmapDrawable) a.getDrawable(R.styleable.myview_myview_background);
Log.d("","得到背景图");
if (dra != null) {
Log.d("drawable", "" + dra.getIntrinsicWidth());
bitmapBackground = dra.getBitmap();
} else {
bitmapBackground = BitmapFactory.decodeResource(getResources(), R.mipmap.cc);
}
int paintWidth=a.getDimensionPixelOffset(R.styleable.myview_myview_paintwidth,100);
paintRect.setStrokeWidth(paintWidth);