自定义组件属性定义获取
2017-11-17 16:29
316 查看
<?xml version="1.0" encoding="utf-8"?> <resources> <!--定义名字叫MyAttributeView属性集合--> <declare-styleable name="MyAttributeView"> <!--定义一个名字叫my_name并且类型是string的属性--> <attr name="my_name" format="string"/> <!--定义一个名字叫my_age并且类型是integer的属性--> <attr name="my_age" format="integer"/> <!--定义一个名字叫my_bg并且类型是reference|color的属性--> <attr name="my_bg" format="reference|color"/> </declare-styleable></resources>
public class MyAttributeView extends View {
private int myAge;
private String myName;
private Bitmap myBg;
public MyAttributeView(Context context, AttributeSet attrs) {
super(context, attrs);
//获取属性三种方式
//1.用命名空间取获取
String age = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","my_age");
String name = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","my_name");
String bg = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","my_bg");
// System.out.println("age=="+age+",name=="+name+",bg==="+bg);
//2.遍历属性集合
for(int i=0;i<attrs.getAttributeCount();i++){
System.out.println(attrs.getAttributeName(i)+"====="+attrs.getAttributeValue(i));
}
//3.使用系统工具,获取属性
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyAttributeView);
for(int i=0;i<typedArray.getIndexCount();i++){
int index = typedArray.getIndex(i);
switch (index){
case R.styleable.MyAttributeView_my_age:
myAge = typedArray.getInt(index,0);
break;
case R.styleable.MyAttributeView_my_name:
myName = typedArray.getString(index);
break;
case R.styleable.MyAttributeView_my_bg:
Drawable drawable = typedArray.getDrawable(index);
BitmapDrawable drawable1 = (BitmapDrawable) drawable;
myBg = drawable1.getBitmap();
break;
}
}
// 记得回收
typedArray.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
canvas.drawText(myName+"---"+myAge,50,50,paint);
canvas.drawBitmap(myBg,50,50<
4000
/span>,paint);
}
}
相关文章推荐
- SL - 整理 - 定义Dependency属性(使自定义组件属性能被绑定)
- React组件自定义属性的定义及使用
- 属性(Attribute)资源使用自定义组件,并指定属性资源中定义的属性
- dorado自定义组件虚拟属性的设置和获取
- 自定义View如何定义和使用自己的属性
- css手势状态定义属性cursor和自定义鼠标手势详解
- js 中设置或获取自定义属性的方法setAttribute getAttribute attributes
- 说说Android 两种为自定义组件添加属性的使用方法和区别
- 使用反射获取枚举的自定义属性Attribute及其他使用方式
- UGUI组件获取及属性设置方法
- option自定义属性获取
- JS 如何获取自定义属性
- 自定义View(一):自定义属性获取
- 自定义枚举类型注释属性,并在程序中获取
- 说说Android 两种为自定义组件添加属性的使用方法和区别
- highcharts图表组件通过设置tooltip属性自定义数据提示信息
- jquery获取自定义属性(attr和prop)实例介绍
- layui select获取自定义属性方法
- js 点击a标签 获取a的自定义属性
- 用RTTI方法获取组件属性的类