Android自定义属性
来源:互联网 发布:神雕侠侣06版源码 编辑:程序博客网 时间:2024/06/05 14:16
Android自定义属性
我们在使用自定义组件的组件的时候,经常需要自定义一些额外的属性。那么,下面我们来看看怎么自定义属性。
自定义属性可以分为三步:
第一步:我们需要在
res/values/
文件夹下面创建一个XML文件attrs.xml
<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="Demo"> <attr name="text" format="string"></attr> <attr name="type" format="integer"></attr> <attr name="textSize" format="dimension"></attr> </declare-styleable></resources>
补充一点:
1.
declear-styleable
标签里面的name
属性在java代码中变成属性数组的名字
2.attr
标签则是我们自定义的属性,format
代表数据类型,它的可选值有string , integer , dimension , reference , color , enum。注意啦,都是小写。第二步: 在我们自定义的控件类的构造方法中获取属性值:
public DemoView(Context context, AttributeSet attrs) { super(context, attrs); //添加一个视图到该控件 View view = inflate(context, R.layout.test,null); addView(view); //获取自定义属性 TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Demo); String text = typedArray.getString(R.styleable.Demo_text); int index = typedArray.getInt(R.styleable.Demo_type, 0); float dimension = typedArray.getDimension(R.styleable.Demo_textSize, 12); typedArray.recycle(); TextView tv = (TextView) view.findViewById(R.id.tv); tv.setText(text); tv.setTextSize(dimension);}
注意点:在取值完成之后一定要回收
在自定义控件中使用属性
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:myAttrs="http://schemas.android.com/apk/res/com.example.defineattrs" android:layout_width="match_parent" android:layout_height="match_parent" > <com.example.defineattrs.DemoView android:layout_width="match_parent" android:layout_height="match_parent" myAttrs:text="自定义的属性" myAttrs:type="1" myAttrs:textSize="30dp" > </com.example.defineattrs.DemoView></RelativeLayout>
注意点:当我们使用自定义属性时,需要添加命名控件
xmlns:myAttrs="http://schemas.android.com/apk/res/com.example.defineattrs"
.这里myAttrs可以随便写,命名空间的最末尾res/
后面一段需要改成我们项目对应的包名。用自定义控件时要用全类名。
0 0
- Android自定义控件 自定义属性
- Android自定义view自定义属性
- Android 自定义控件 自定义属性
- Android自定义View-自定义属性
- android 自定义控件自定义属性
- Android自定义View-自定义属性
- android 自定义控件属性
- android自定义属性
- Android自定义属性
- android 里自定义属性
- android自定义属性
- Android自定义控件属性
- Android 中自定义属性
- Android自定义属性
- android 自定义控件属性
- android自定义属性
- android 自定义xml属性
- android使用自定义属性
- linux基础——linux下数据库连接池的原理及编程实现
- IOS绘图详解
- Android 中Java和JavaScript如何交互?
- Java产品设计-微信开发设计1《职业前言》
- openMVG+openMVS+VS2015配置全过程(详细参数设置+截图)
- Android自定义属性
- Javascript相关面试题目
- Java产品设计-微信开发设计2《创业产品定位与分析》
- JS比较数组差异
- Java产品设计-微信开发设计3《微信产品设计图》
- UNITY 路线
- 【openCV入门之二】 快速上手
- java基本类型数组初始化
- UVA 10305 拓扑排序