昨天分享了简单的自定义View里面有用到自定义属性,所以在这里我对自定义属性作出总结。 自定义属性地第一步在Values文件夹下创建一个XML这里XML的名字可以随便起但是一般都是以attrs开头如attrs_circle.xml 先上布局代码然后在对代码中的内容作出总结
文件路径res/values/attrs_circle.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyCircleView"> <attr name="color" format="color"/> </declare-styleable> </resources>declare-styleable自定义属性 attr中的format中的Color指的是格式 我这里的代码代表颜色除了color之外还有reference代表的是资源id,dimension代表尺寸,当然这里还有一些基本的数据类型这里我就不做过多的解释
自定义属性说完之后那么现在就来说说怎么使用在我们自定义View中这里我只贴出自定义属性这块代码,其他代码请在自定义VIew成长子路(一)中查看
public MyCircleView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); //解析自定义属性 TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCircleView); mColor =typedArray.getColor(R.styleable.MyCircleView_color,Color.RED); }TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCircleView);
attrs参数为自定义VIew中构造中 R.styleable.MyCircleView为 declare-styleable后面的name
typedArray.getColor(R.styleable.MyCircleView_color,Color.RED); R.styleable.MyCircleView_color 为attr中的name Color.RED为当我们没有设置时默认的颜色
布局文件中使用
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:circle="http://schemas.android.com/apk/res-auto" android:id="@+id/activity_main2" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="20dp" tools:context="com.example.as.myapplication.Main2Activity"> <com.example.as.myapplication.MyCircleView android:layout_width="wrap_content" android:layout_height="wrap_content" circle:color="#ffff"/> </RelativeLayout>xmlns:circle=”http://schemas.android.com/apk/res-auto”这句代码是对我们自定义属性的声明
circle:color=”#ffff”这句代码是对自定义属性声明后进行使用 好了自定义属性就在这了欢迎补充