android的自定义属性
2015-10-10 14:49
429 查看
感觉android官方定义的组件不够用时,可以选择自定义组件,自定义组件通常分为3步,
第一步:在res/values文件下定义一个diy.xml文件,代码如下。
该文件是定义属性名和格式的地方,需要用到<declare-styleable
name="ToolBar"> </declare-styleable>包围所有属性。其中name为该属性集的名字,主要用途是标识该属性集。在第三步获取某属性标识时,会用到该属性集名字,例如:“R.styleable.ToolBar_buttonNum”,
而类似
则为属性名以及属性的类型,亦有
这种形式
第二步:在布局文件xml中使用该属性。
注意要先声明:
前面的toolbar可以换成任意字符,但是后面的url地址最后一部分需用上包名。
在android studio中会出现无法识别的问题,需要替换成
第三步:在自定义组件中,可以如下获得xml中定义的值
第一步:在res/values文件下定义一个diy.xml文件,代码如下。
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="ToolBar"> <attr name="buttonNum" format="integer"/> <attr name="itemBackground" format="reference|color"/> </declare-styleable> </resources>
该文件是定义属性名和格式的地方,需要用到<declare-styleable
name="ToolBar"> </declare-styleable>包围所有属性。其中name为该属性集的名字,主要用途是标识该属性集。在第三步获取某属性标识时,会用到该属性集名字,例如:“R.styleable.ToolBar_buttonNum”,
而类似
<attr name="buttonNum" format="integer"/>
则为属性名以及属性的类型,亦有
<attr name="testEnum"> <enum name="fill_parent" value="-1"/> <enum name="wrap_content" value="-2"/> </attr>
这种形式
第二步:在布局文件xml中使用该属性。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:toolbar="http://schemas.android.com/apk/res/cn.zzm.toolbar" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <cn.zzm.toolbar.ToolBar android:id="@+id/gridview_toolbar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:background="@drawable/control_bar" android:gravity="center" toolbar:buttonNum="5" toolbar:itemBackground="@drawable/control_bar_item_bg"/> </RelativeLayout>
注意要先声明:
xmlns:toolbar="http://schemas.android.com/apk/res/cn.zzm.toolbar"
前面的toolbar可以换成任意字符,但是后面的url地址最后一部分需用上包名。
在android studio中会出现无法识别的问题,需要替换成
xmlns:toolbar="http://schemas.android.com/apk/res-auto"的形式
第三步:在自定义组件中,可以如下获得xml中定义的值
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ToolBar); buttonNum = a.getInt(R.styleable.ToolBar_buttonNum, 5); itemBg = a.getResourceId(R.styleable.ToolBar_itemBackground, -1); a.recycle();在自定义组件的构造函数中,用
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ToolBar);获得对属性集的引用,然后即可用“a”的各种方法来获取相应的属性值。
相关文章推荐
- android权限问题
- Android获取TextView文本实际宽度
- 新建一个Android项目helloWorld
- android ListView详解
- AndroidStudio 安装后报错解决办法
- AndroidStudio 安装后报错解决办法
- 怎么调用android 自带的图片浏览器
- Android 注解框架 Butterknife的核心代码分析笔记
- Android Studio配置CheckStyle
- Android系统 小米/三星/索尼 应用启动图标未读消息数(BadgeNumber)动态提醒
- android布局及其常用属性
- android ndk ABI Management
- android Toast工具类
- Android社会化分享的实现方法
- android WebView java与js相互调用
- Android-Universal-Image-Loader 图片异步加载类库的使用(超详细配置)
- android log 学习
- Android社会化分享功能的实现步骤
- Android 主流分辨率
- 毛玻璃效果demo