您的位置:首页 > 其它

自定义View属性的使用

2016-05-15 15:07 381 查看

自定义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()方法。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: