自定义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);
}
- 在代码中直接new一个Custom View实例的时候,会调用第一个构造函数.这个没有任何争议.
- 在xml布局文件中调用Custom View的时候,会调用第二个构造函数.这个也没有争议.
- 在xml布局文件中调用Custom View,并且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的宽度
@Override protected void onFinishInflate() { super.onFinishInflate(); if (mRightId!=0){ rightMenuView = findViewById(mRightId); } }***************************************************************************************************************************