复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124<?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,paint); } }
最后
以上就是大气台灯最近收集整理的关于自定义组件属性定义获取的全部内容,更多相关自定义组件属性定义获取内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复