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

本文介绍了自定义View的三种构造方法及应用场景,并详细讲解了如何通过XML文件配置自定义属性,包括声明自定义属性、在Activity布局文件中引用自定义View及其属性,以及如何在代码中获取这些属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义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的宽度

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值