自定义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()方法。
相关文章推荐
- Matlab分析音频
- Android自定义圆角对话框
- Java面向对象之封装
- Git学习 -- 远程操作遇到error: failed to push some refs to问题解决方法
- 小米平板刷机教程
- 使用nodejs的net模块创建TCP服务器
- 永远不要祈求生活来怜悯你,你只能让自己变的更强
- 统一编址&独立编址
- CAN与CANOpen(二)
- 事件处理模型
- python学习笔记3—流程控制if、for、while
- 华中农业大学第四届程序设计大赛网络同步赛题目
- React-Native系列Android——通信数据模型分析
- 高仿QQ源码 界面(3)
- Spark Shuffle内幕
- LeetCode 104. Maximum Depth of Binary Tree
- 初识python(1)
- View
- SpringMVC的简单传值(实现代码)
- Grunt 之 watch 和 livereload