码迷,mamicode.com
首页 > 其他好文 > 详细

自定义控件(视图)28期笔记06:自定义控件之使用系统控件(自定义属性)

时间:2015-09-28 11:35:23      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

1. 为新控件添加自定义的属性:

主要步骤:

(1)在attrs.xml文件中声明属性,有 属性名:name  和  格式:format:

1 <declare-styleable name="MyToggleBtn">     // 声名属性集的名称,即这些属性是属于哪个控件的。
2       <attr name="current_state" format="boolean"/> // 声名属性 current_state   格式为 boolean 类型
3       <attr name="slide_button" format="reference"/> // 声名属性 slide_button   格式为 reference 类型
4 </declare-styleable> 

所有的format类型,如下:

1 reference        引用
2 color            颜色
3 boolean          布尔值
4 dimension        尺寸值
5 float            浮点值
6 integer          整型值
7 string           字符串
8 enum             枚举值

 

(2)在布局文件中使用新属性,使用之前必须先声明命名空间,如:

1  xmlns:heima="http://schemas.android.com/apk/res/com.himi.togglebtn"

说明:

xmlns 是XML name space 的缩写;

heima 可为任意写符

http://schemas.android.com/apk/res/ 此为android固定格式;

com.itheima.mytogglebtn 此应用的包名,如manifest配置文件中一致。

 

布局文件:

1 <com.itheima.mytogglebtn.MyToggleButton
2         xmlns:heima="http://schemas.android.com/apk/res/com.himi.mytogglebtn"
3         android:layout_width="wrap_content"
4         android:layout_height="wrap_content"
5         heima:slide_button="@drawable/slide_button" />

 

(3)在自定义View的构造方法中,通过解析AttributeSet对象,获得所需要的属性值

1 TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyToggleBtn);    // 由attrs 获得 TypeArray

 

2. 下面通过一个案例解析说明上面的过程,如下:

(1)首先新建一个新的"Android"工程,命名为"自定义属性",如下:

技术分享

 

(2)自定义一个MyView继承自View,如下:

技术分享

 (3)新建一个xml文件,命名为attrs.xml,放在res/values文件夹下,如下:

通过查看源码SDT/platforms/android-14/data/res/values/attrs.xml,获知如何什么一个attr(属性)格式:

 

 技术分享

(4)在activity_main.xml文件下修改命名空间,使用上面定义的属性,如下:

 1 <RelativeLayout 
 2     xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:heima="http://schemas.android.com/apk/res/com.himi.myattrsdemo"
 4     xmlns:tools="http://schemas.android.com/tools"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     tools:context="com.himi.myattrsdemo.MainActivity" >
 8 
 9     <com.himi.myattrsdemo.MyView
10         android:layout_width="wrap_content"
11         android:layout_height="wrap_content"
12         android:layout_centerHorizontal="true"
13         android:layout_centerVertical="true"
14         android:background="@drawable/ic_launcher"
15         
16         heima:test_msg="@string/app_name"
17         heima:test_bitmap="@drawable/ic_launcher"
18          />
19 
20 </RelativeLayout>

(5)在自定义的MyView的构造方法中,通过解析AttributeSet对象,获得所需要的属性值:

 

自定义控件(视图)28期笔记06:自定义控件之使用系统控件(自定义属性)

标签:

原文地址:http://www.cnblogs.com/hebao0514/p/4843411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!