完成自定义属性需要4个步骤,完美解决。
1. 通过 为自定义View添加属性
2. 在xml中为相应的属性声明属性值
3. 在运行时(一般为构造函数)获取属性值
4. 将获取到的属性值应用到View
1、添加自定义属性:
在attrs.xml 文件中,定义 declare-styleable 如下所示
2、申明属性:local 自定义名,添加资源文件路径;
3、布局文件中引用
4、自定义文件中,获取属性,设置到View
public CarsonView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); // 获取属性 TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.BtnBackColor); int color = array.getColor(R.styleable.BtnBackColor_btnColor, 0x00ffff); String dontdong = array.getString(R.styleable.BtnBackColor_btnText); // 应用属性到对应view setText(dontdong); setTextColor(color); array.recycle(); \回收资源否则内存泄露 }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)