1.因为是自定义属性,所以要创建一个属性的xml文件,这里在value文件夹下创建一个attrs.xml文件

<?xml version="1.0" encoding="utf-8"?><resources>    <!--声明的属性集-->    <declare-styleable name="MyRect">        <!--自定义的属性,format为color-->        <attr name="MyRect_Color" format="color"/>    </declare-styleable></resources>

2.自定义的View都必须继承自View,除空的构造方法外还要添加含有AttributeSet参数的构造函数,用于资源解析器的解析。

/** * Created by tongs on 2016/4/12. * email:tongsdroid@gmail.com */public class MyRect extends View {    public MyRect(Context context) {        super(context);    }    /** * 由资源解析器来解析 */    public MyRect(Context context, AttributeSet attrs) {        super(context, attrs);        //获取xml中的属性和自定义的MyRect属性集.        TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.MyRect);        //color的默认值为0x00ff0000        int color = ta.getColor(R.styleable.MyRect_MyRect_Color,0x00ff0000);        setBackgroundColor(color);        //调用完obtain后要记得recycle回收        ta.recycle();    }}

3.在布局文件中就可以引入自定义的控件MyRect了,也可以在这个文件中引用自定义的属性my_rect:MyRect_Color
但要声明命名空间xmlns:my_rect="http://schemas.android.com/apk/res-auto"

<?xml version="1.0" encoding="utf-8"?><LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android" xmlns:my_rect="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:orientation="vertical" tools:context="com.android.tongs.custom_view.MainActivity">    <com.android.tongs.custom_view.MyRect  android:layout_width="100dp" android:layout_height="100dp" my_rect:MyRect_Color="#ff00ff" /></LinearLayout>

更多相关文章

  1. SpringBoot 2.0 中 HikariCP 数据库连接池原理解析
  2. AndroidStudio 2.0 导入(.so)文件方法,以科大讯飞(20021)为例
  3. android 世界各国英文简写代码 资源文件
  4. Android中Fragment的使用,切换和返回等问题-刘宇
  5. 【Android(安卓)Developers Training】 78. 序言:执行网络操作
  6. android Ubuntu adb: cannot execute binary file: 可执行文件格
  7. Picasso源码解析
  8. Android(安卓)Studio 签名证书文件在build.gradle(app)中配置
  9. Android异步加载访问网络图片-解析json

随机推荐

  1. 几道和「广度优先搜索」有关的算法面试题
  2. GitHub 告别中文仓库刷榜/霸榜
  3. 数据结构与算法——图最短路径
  4. GitHub 热门:微软新开源的 Python 静态类
  5. 数据结构与算法——图论基础与图存储结构
  6. 一道简约而不简单的算法题--数据流的中位
  7. GitHub 热门:Python 算法大全,Star 超过 2
  8. GitHub 热门:别再用 print 输出来调试代码
  9. 真香!GitHub 核心功能都免费开放了
  10. 一网打尽!二分查找解题模版与题型全面解析