自定义View-View的构造函数

需要重写的构造方法

  • public CustomView(Context context) {super(context);}

  • public CustomView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); }//通过attrs获取自定义的属性

  • public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}

  • 获取自定义属性

    • 在res/values 文件夹下建立 attrs.xml ,内容如下:
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <!--所属的自定义的View-->
    <declare-styleable name="CicleView">
        <!--属性名称和类型-->
        <attr name="size" format="integer">
            <!--属性的指定的值,这个是可选的-->
            <enum name="normal" value="1" />
        </attr>
    </declare-styleable>
    </resources>
    
    • 在layout的下xml文件中使用自定义View和自定义属性,内容如下:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
    
    <com.example.administrator.aidldemo.anim.object.CicleView
        android:id="@+id/cv_demo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:size="normal" />
    </LinearLayout>
    
    • 在自定义View中获取到自定义属性
      public CicleView(Context context) {
        super(context);
        init(context, null);
    }
    
    public CicleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }
    
    public CicleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }
    
    private void init(Context context, @Nullable AttributeSet attrs) {
        if (attrs != null) {
            TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CicleView);
            int size = array.getInt(R.styleable.CicleView_size, 0);
            array.recycle();
        }
    }
    

猜你喜欢

转载自blog.csdn.net/genmenu/article/details/88868488
今日推荐