一.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();
}
本文详细介绍了在Android开发中如何使用attr文件自定义视图属性,并通过TypedArray获取这些属性值,包括字符串、浮点数、颜色、尺寸、图片及引用类型资源。
476

被折叠的 条评论
为什么被折叠?



