自定义View之构造方法和用法

来源:互联网 发布:红帽linux 10天就重启 编辑:程序博客网 时间:2024/04/30 16:04

自定义view三个构造方法:

    public SwipeRecycleView(Context context) {        this(context,null);    }    public SwipeRecycleView(Context context, @Nullable AttributeSet attrs) {        this(context, attrs,0);    }    public SwipeRecycleView(Context context, @Nullable AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);       }

  1. 在代码中直接new一个Custom View实例的时候,会调用第一个构造函数.这个没有任何争议.
  2. 在xml布局文件中调用Custom View的时候,会调用第二个构造函数.这个也没有争议.
  3. 在xml布局文件中调用Custom View,并且Custom View标签中还有自定义属性时,这里调用的还是第二个构造函数.
至于自定义属性的获取,通常是在构造函数中通过obtainStyledAttributes函数实现的.这里先介绍一下如何生成Custom View的自定义属性.

第一步:Custom View添加自定义属性主要是通过declare-styleable标签为其配置自定义属性,具体做法是: 在res/values/目录下增加一个resources xml文件,示例如下(res/values/attrs.xml):其他也可以,一般定义成attrs

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="SwipeMenuLayout">        <attr name="right_menu_id" format="reference"/>    </declare-styleable></resources>
第二步

在设置自定义属性之前,我们首先要在主Activity的布局文件中调用我们的Custom View,并且为其设置特定的属性.

<com.android.lyf.recycle.SwipeMenuLayout 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="70dp"    android:id="@+id/swipe_menu"    android:background="@color/white"    android:orientation="horizontal"    app:right_menu_id="@+id/ll_right_menu"    >
注意:在给自定义属性赋值时,首先需要增加自定义属性的命名空间,例如: xmlns:app=”http://schemas.Android.com/apk/res-auto”,android Studio推荐使用res-auto,在Eclipse中需要使用Custom View所在的包名: xmlns:app=”http://schemas.android.com/apk/com.kevintan.eventbussample.view”

第三步:

TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SwipeMenuLayout);mRightId  = typedArray.getResourceId(R.styleable.SwipeMenuLayout_right_menu_id, 0);typedArray.recycle();
我是为了得到左边menu的宽度

@Overrideprotected void onFinishInflate() {    super.onFinishInflate();    if (mRightId!=0){         rightMenuView = findViewById(mRightId);    }}
***************************************************************************************************************************



原创粉丝点击