自定义view规范步骤步骤
自定义属性
像android:layout_width和android:padding这种以android开头的属性是系统自带的,还可以添加自定义属性。
1. 在res/values文件夹下建立xml,如attrs.xml(命名随意)。
2. 在View的构造方法中解析自定义属性的值并做相应处理。
1 public CircleView(Context context) { 2 super(context); 3 init(); 4 } 5 6 public CircleView(Context context, @Nullable AttributeSet attrs) { 7 this(context, attrs, 0); 8 } 9 10 public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 11 super(context, attrs, defStyleAttr);
// 加载自定义属性集合CircleView,接着解析CircleView属性集合中的circle_color属性,它的id是R.styleable.CircleView_circle_color
12 TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircleView); 13 mColor = typedArray.getColor(R.styleable.CircleView_circle_color, Color.GRAY);
// 释放资源 14 typedArray.recycle(); 15 init(); 16 }
3. 在布局文件中使用自定义属性。
为使用,必须在布局文件中添加schemas声明(命名空间)
xmlns:app="http://schemas.android.com/apk/res-auto"
1 <com.example.jkdemo.CircleView 2 android:id="@+id/circleView" 3 android:layout_width="100dp" 4 android:layout_height="100dp" 5 android:text="啊啊啊" 6 android:gravity="center" 7 android:layout_gravity="center" 8 app:circle_color="@color/colorAccent" 9 />