自定义View属性的使用

自定义View属性的使用

  • 创建 /res/values/attrs.xml
    内容如下:
    <?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ClickTransparentButton">
        <attr name="isNight" format="boolean"/>
    </declare-styleable>
</resources>

  • 在xml文件中使用自定义view的属性
在开头添加命名空间,即可自动引入自定义属性(isNight)

xmlns:custom=”http://schemas.android.com/apk/res-auto”

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f00"
    tools:context="com.example.zero.testview.MainActivity">


    <com.example.zero.testview.ClickTransparentButton
        android:id="@+id/imgBtn"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_centerInParent="true"
        android:scaleType="fitCenter"
        custom:isNight="true"
        android:src="@drawable/img" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"/>


</RelativeLayout>

Java文件中获取自定义属性的方式,通过TypeArray来获取自定义View的属性,代码如下:

     public ClickTransparentButton(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ClickTransparentButton);
        isNight = ta.getBoolean(R.styleable.ClickTransparentButton_isNight, false);
        adjustAlpha(isNight);
        ta.recycle();
        setOnTouchListener(this);
    }

注意通过TypeArray获取到自定义View属性后,应该及时调用其recycle()方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值