Custom View-View constructor

Construction method that needs to be rewritten

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

  • public CustomView(Context context, @Nullable AttributeSet attrs) {super(context, attrs); }//Get custom attributes through attrs

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

  • Get custom attributes

    • Create attrs.xml under the res/values ​​folder, the content is as follows:
    <?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>
    
    • Use custom View and custom attributes in the xml file of the layout, as follows:
    <?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>
    
    • Get custom attributes in custom 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();
        }
    }
    

Guess you like

Origin blog.csdn.net/genmenu/article/details/88868488