一.attr 文件
attr 是 values 目录下的资源文件,新建项目是没有 attr 文件的,我们自己新建一个出来放到 values 里面就行

attr 中的自定义属性样式
<declare-styleable name="MyView">
<attr name="name" format="string"></attr>
<attr name="info" format="float"></attr>
</declare-styleable>
二.获取属性
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
setOnTouchListener(touchListener);
// 获取属性集合 TypedArray
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
// 获取字符串
String name = typedArray.getString(R.styleable.MyView_string);
// 获取 float ,后面是默认值
float age = typedArray.getFloat(R.styleable.MyView_float,1);
// 获取颜色值,后面是默认值
int color = typedArray.getFloat.getColor(R.styleable.MyView_color, Color.BLACK);
// 获取 dimension,后面是默认值
int dimens = typedArray.getDimension(R.styleable.MyView_dimens, 0);
// 获取图片
Drawable drawable = typedArray.getDrawable(R.styleable.MyView_drawable);
// 获取引用类型,这里获取的是引用类型资源的资源 id ,然后还得我们自己用这个id 才恩那个拿到引用了;类型资源对象
int resourceId = typedArray.getResourceId(R.styleable.MyView_info, 0);
// 用完要关闭回收资源,必须的强制性的
typedArray.recycle();
}版权声明:本文为yuemingxingxing原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。